Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.gfl.linewise.chat.ui;
- import android.content.BroadcastReceiver;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.content.ServiceConnection;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.support.v4.content.LocalBroadcastManager;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ListView;
- import android.widget.Spinner;
- import android.widget.Toast;
- import com.alshvets.core.structure.helpers.Dialogs;
- import com.alshvets.core.structure.helpers.Logger;
- import com.alshvets.core.structure.models.error.IError;
- import com.alshvets.core.structure.requests.mock.ICallback;
- import com.gfl.linewise.Constants;
- import com.gfl.linewise.R;
- import com.gfl.linewise.api.models.Session;
- import com.gfl.linewise.api.models.UserProfile;
- import com.gfl.linewise.api.models.responses.Profiles;
- import com.gfl.linewise.api.models.responses.UserInfo;
- import com.gfl.linewise.api.requests.GetAllUsersRequest;
- import com.gfl.linewise.api.requests.GetUserInfoRequest;
- import com.gfl.linewise.chat.ChatManager;
- import com.gfl.linewise.chat.ChatUsersSearch;
- import com.gfl.linewise.chat.MessageService;
- import com.gfl.linewise.chat.adapters.ListUsersAdapter;
- import com.gfl.linewise.chat.adapters.UserSpinnerAdapter;
- import com.gfl.linewise.chat.models.ChatUser;
- import com.gfl.linewise.chat.models.ChatUsers;
- import com.gfl.linewise.chat.models.Message;
- import com.gfl.linewise.chat.models.UserSpinner;
- import com.gfl.linewise.preferences.AppPreference;
- import com.gfl.linewise.ui.activities.CustomTitleActivity;
- import com.google.gson.Gson;
- import com.parse.FindCallback;
- import com.parse.GetCallback;
- import com.parse.ParseException;
- import com.parse.ParseObject;
- import com.parse.ParseQuery;
- import com.parse.ParseUser;
- import com.sinch.android.rtc.PushPair;
- import com.sinch.android.rtc.messaging.MessageClient;
- import com.sinch.android.rtc.messaging.MessageClientListener;
- import com.sinch.android.rtc.messaging.MessageDeliveryInfo;
- import com.sinch.android.rtc.messaging.MessageFailureInfo;
- import com.sinch.android.rtc.messaging.WritableMessage;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Hashtable;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Set;
- import static android.text.TextUtils.isEmpty;
- import static com.alshvets.core.structure.helpers.Dialogs.showToast;
- import static com.gfl.linewise.helpers.Intents.startUserActivity;
- public class ListUsersActivity extends CustomTitleActivity implements ListUsersAdapter.OnChatUserClickListener, View.OnClickListener {
- private ListView usersListView;
- private List<UserProfile> allUsersServerResponseList = new ArrayList<>();
- private List<UserProfile> allChatUsersList = Collections.synchronizedList(new ArrayList());
- private Hashtable<String, Message> firstUserMessages = new Hashtable<>();
- private ListUsersAdapter adapter;
- private MessageService.MessageServiceInterface messageService;
- private ServiceConnection serviceConnection = new MyServiceConnection();
- private MessageClientListener messageClientListener = new MyMessageClientListener();
- private HashMap<String, String> allChatUsers = new HashMap<>();
- private UserSpinnerAdapter userSpinnerAdapter;
- private ParseUser currentUser;
- private String userObjectId;
- private String serverUserId;
- private EditText editTextMessage;
- private volatile List<UserProfile> allChatUsersListOrdered;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_list_users);
- Logger.debug(getClass(), "ListUsersActivity onCreate");
- currentUser = ParseUser.getCurrentUser();
- if (currentUser != null) {
- bindService(new Intent(this, MessageService.class), serviceConnection, BIND_AUTO_CREATE);
- } else {
- Logger.debug(getClass(), "currentUser");
- }
- mProgressDialog.show();
- mProgressDialog.setCancelable(true);
- registerBroadcastReceiver();
- buttonBack = findViewById(R.id.button_back);
- buttonBack.setOnClickListener(this);
- usersListView = (ListView) findViewById(R.id.usersListView);
- adapter = new ListUsersAdapter(this, this, allChatUsersList, firstUserMessages);
- usersListView.setAdapter(adapter);
- usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> a, View v, int i, long l) {
- // startChatWithUser();
- getPointsOfCurrentUser(allChatUsersList.get(i));
- }
- });
- editTextMessage = (EditText) findViewById(R.id.editTextMessage);
- Button btnSendComment = (Button) findViewById(R.id.btnSendComment);
- btnSendComment.setOnClickListener(this);
- getAllUsers();
- // ChatManager.getInstance().bindService(this);
- }
- private void getPointsOfCurrentUser(final UserProfile userProfile) {
- Session session = new Session(AppPreference.getInstance().getSession());
- new GetUserInfoRequest(session, new ICallback<UserInfo>() {
- @Override
- public void onSuccess(UserInfo userInfo) {
- Logger.debug(getClass(), "GetUserInfoRequest: OK");
- if (userInfo != null) {
- // updateUserInfo(userInfo);
- AppPreference.getInstance().setUserInfoResponse(new Gson().toJson(userInfo));
- startChatWithUser(userProfile);
- }
- }
- @Override
- public void onError(IError error) {
- Logger.error(getClass(), "GetUserInfoRequest error");
- }
- }).execute();
- }
- private void startChatWithUser(final UserProfile userProfile) {
- String username = userProfile.getEmail();
- ParseQuery<ParseUser> query = ParseUser.getQuery();
- query.setLimit(1000);
- query.whereEqualTo("username", username);
- query.findInBackground(new FindCallback<ParseUser>() {
- @Override
- public void done(List<ParseUser> userList, ParseException e) {
- if (e == null) {
- //start the messaging activity
- Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
- intent.putExtra(MessagingActivity.RECIPIENT_ID, userList.get(0).getObjectId());
- intent.putExtra(MessagingActivity.USER_ID, userProfile.getId());
- // intent.putExtra(MessagingActivity.POINTS, points);
- intent.putExtra(MessagingActivity.PHOTO_URL, userProfile.getPhoto());
- startActivity(intent);
- } else {
- safeClose(mProgressDialog);
- Toast.makeText(getApplicationContext(),
- "Error loading user list",
- Toast.LENGTH_LONG).show();
- }
- }
- });
- }
- @Override
- public void onResume() {
- super.onResume();
- setTitle(getString(R.string.title_activity_messaging));
- getAllUsers();
- }
- private void registerBroadcastReceiver() {
- BroadcastReceiver receiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- Boolean success = intent.getBooleanExtra("success", false);
- if (!success) {
- safeClose(mProgressDialog);
- Toast.makeText(getApplicationContext(), "Sorry, messaging service not working.",
- Toast.LENGTH_LONG).show();
- }
- }
- };
- LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter
- ("com.gfl.linewise.chat.ui.ListUsersActivity"));
- }
- public void getAllUsers() {
- Session session = new Session(AppPreference.getInstance().getSession());
- new GetAllUsersRequest(session, new ICallback<Profiles>() {
- @Override
- public void onSuccess(Profiles profiles) {
- Logger.debug(getClass(), "GetAllUsersRequest: All users received");
- if (profiles != null) {
- allUsersServerResponseList = profiles.getProfiles();
- if (allUsersServerResponseList != null) {
- //to initialize send message layout
- getAllChatUsers();
- if (currentUser != null) {
- ParseQuery<ParseObject> query = ParseQuery.getQuery(ChatManager.CHAT_USER_FRIENDS);
- query.getInBackground(currentUser.get("chatUserObjectId").toString(), new GetChatUserListCallback());
- } else {
- safeClose(mProgressDialog);
- Logger.debug(getClass(), "currentUser == null");
- }
- }
- }
- }
- @Override
- public void onError(IError error) {
- Logger.error(getClass(), "GetAllUsersRequest error");
- safeClose(mProgressDialog);
- showToast(ListUsersActivity.this, R.string.inet_problems);
- }
- }).execute();
- }
- private void getAllChatUsers() {
- String currentUserId = "";
- if(ParseUser.getCurrentUser() != null) {
- currentUserId = ParseUser.getCurrentUser().getObjectId();
- } else {
- return;
- }
- //don't include yourself in the list
- ParseQuery<ParseUser> query = ParseUser.getQuery();
- query.setLimit(1000);
- query.whereNotEqualTo("objectId", currentUserId);
- query.findInBackground(new FindCallback<ParseUser>() {
- public void done(List<ParseUser> userList, ParseException e) {
- if (e == null) {
- for (int i = 0; i < userList.size(); i++) {
- allChatUsers.put(userList.get(i).getUsername(), userList.get(i).getObjectId());
- }
- initializeSendMessageSection();
- } else {
- Toast.makeText(getApplicationContext(),
- "Error loading user list",
- Toast.LENGTH_LONG).show();
- }
- }
- });
- }
- private void initializeSendMessageSection() {
- //convert allUsersServerResponseList into allUsersServerResponseMap <Email, UserProfile>
- Map<String, UserProfile> allUsersServerResponseMap = new HashMap<>();
- for (UserProfile i : allUsersServerResponseList) allUsersServerResponseMap.put(i.getEmail(), i);
- //all server users that have chat account Map<chat Object id, UserSpinner>
- final List<UserSpinner> allUsersWithChat = new ArrayList<>();
- for (Entry<String, UserProfile> entry : allUsersServerResponseMap.entrySet()) {
- String key = entry.getKey();
- UserProfile value = entry.getValue();
- if(allChatUsers.containsKey(key)){
- String objectId = allChatUsers.get(key);
- UserSpinner userSpinner = new UserSpinner(objectId, key, value);
- allUsersWithChat.add(userSpinner);
- }
- }
- Logger.debug(getClass(), "initializing spinner adapter");
- Spinner spinner = (Spinner) findViewById(R.id.usersSpinner);
- userSpinnerAdapter = new UserSpinnerAdapter(this, allUsersWithChat);
- spinner.setAdapter(userSpinnerAdapter);
- spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> parent, View view,
- int pos, long id) {
- serverUserId = allUsersWithChat.get(pos).getUserProfile().getId();
- userObjectId = allUsersWithChat.get(pos).getObjectId();
- userSpinnerAdapter.notifyDataSetChanged();
- }
- @Override
- public void onNothingSelected(AdapterView<?> arg0) {
- }
- });
- }
- private class GetChatUserListCallback implements GetCallback<ParseObject>, ChatUsersSearch.OnChatUsersFoundListener {
- @Override
- public void done(ParseObject parseObject, ParseException e) {
- if (e == null) {
- Logger.debug(getClass(), "Chat: chat list object FOUND " + parseObject.getObjectId());
- String jsonString = (String) parseObject.get("chatUsers");
- Logger.debug(getClass(), "chatUsers json! " + jsonString);
- ChatUsers chatUsers = new Gson().fromJson(jsonString, ChatUsers.class);
- Logger.debug(getClass(), "CHAT FRIENDS SIZE: " + chatUsers.getChatUsers().size());
- if (chatUsers.getChatUsers().size() > 0) {
- ChatUsersSearch chatUsersSearch = new ChatUsersSearch(this);
- chatUsersSearch.startSearch(chatUsers.getChatUsers());
- } else {
- safeClose(mProgressDialog);
- }
- } else {
- if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
- Logger.error(getClass(), "Chat: ParseException.OBJECT_NOT_FOUND");
- safeClose(mProgressDialog);
- } else {
- Logger.error(getClass(), "Chat: unknown error, debug");
- }
- }
- }
- @Override
- public void onChatUsersFound(Hashtable<String, ChatUser> chatUserFriends) {
- Logger.debug(getClass(), "ListUsersActivity onChatUsersFound");
- getChatUsersFromServerUsers(chatUserFriends);
- // ChatManager.getInstance().calculateUnreadMessages(chatUserFriends);
- }
- }
- private void getChatUsersFromServerUsers(Hashtable<String, ChatUser> chatUserFriends) {
- Logger.debug(getClass(), "getChatUsersFromServerUsers");
- Logger.debug(getClass(), "chatFriends size " + chatUserFriends.size());
- Hashtable<String, ChatUser> chatFriends = chatUserFriends;
- for (Entry<String, ChatUser> entry : chatFriends.entrySet()) {
- String key = entry.getKey();
- ChatUser value = entry.getValue();
- Logger.debug(getClass(), "chatUser key" + key);
- Logger.debug(getClass(), "chatUser getSenderId: " + value.getSenderId());
- Logger.debug(getClass(), "chatUser getMessagesAmount: " + value.getMessagesAmount());
- iterateAllChatUsers(key, chatUserFriends.size());
- }
- }
- private void iterateAllChatUsers(final String senderId, final int friendsSize) {
- Logger.debug(getClass(), "iterateAllChatUsers");
- for (Map.Entry<String, ChatUser> entry : ChatManager.getChatUsers().getChatUsers().entrySet()) {
- String key = entry.getKey();
- ChatUser value = entry.getValue();
- Logger.debug(getClass(), "chatUser key" + key);
- Logger.debug(getClass(), "chatUser getSenderId: " + value.getSenderId());
- Logger.debug(getClass(), "chatUser getMessagesAmount: " + value.getMessagesAmount());
- Logger.debug(getClass(), "email of user! " + value.getUsername());
- for (UserProfile userProfile : allUsersServerResponseList) {
- if (userProfile.getEmail().equals(value.getUsername())) {
- allChatUsersList.add(userProfile);
- if (adapter != null) {
- adapter.notifyDataSetChanged();
- }
- getLastMessageByUser(key, userProfile.getId(), friendsSize);
- }
- }
- }
- }
- private void getLastMessageByUser(final String senderId, final String userId, final int friendsSize) {
- Logger.debug(getClass(), "getLastMessageByUser");
- final String currentUserId = currentUser.getObjectId();
- String[] userIds = {currentUserId, senderId};
- ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
- query.whereContainedIn("senderId", Arrays.asList(userIds));
- query.whereContainedIn("recipientId", Arrays.asList(userIds));
- query.orderByDescending("createdAt");
- query.setLimit(1);
- query.findInBackground(new FindCallback<ParseObject>() {
- @Override
- public void done(List<ParseObject> messageList, com.parse.ParseException e) {
- if (e == null) {
- WritableMessage message = new WritableMessage(messageList.get(0).get("recipientId").
- toString(), messageList.get(0).get("messageText").toString());
- Date createdAt = messageList.get(0).getCreatedAt();
- long createdAtMilliseconds = createdAt.getTime();
- Message messageObj = new Message(message.getTextBody(), createdAtMilliseconds);
- firstUserMessages.put(userId, messageObj);
- if (friendsSize <= firstUserMessages.size()) {
- orderChatUsersByMessages();
- }
- }
- }
- });
- }
- private void orderChatUsersByMessages() {
- Logger.debug(getClass(), "orderChatUsersByMessages");
- //create map with userId and Message object
- Map<String, Long> userMessageDateMap = new HashMap<>();
- for (Entry<String, Message> entry : firstUserMessages.entrySet()) {
- long createdMillis = entry.getValue().getCreatedAt();
- userMessageDateMap.put(entry.getKey(), createdMillis);
- }
- Set<Entry<String, Long>> userSet = userMessageDateMap.entrySet();
- //get ordered list with user Id's by time of created message
- List<Entry<String, Long>> userList = new ArrayList<>(userSet);
- Collections.sort(userList, new Comparator<Entry<String, Long>>() {
- public int compare(Entry<String, Long> o1, Entry<String, Long> o2) {
- return (o2.getValue()).compareTo(o1.getValue());
- }
- });
- //convert allChatUsersList into allChatUsersMap
- Map<String, UserProfile> allChatUsersMap = new HashMap<>();
- for (UserProfile i : allChatUsersList) allChatUsersMap.put(i.getId(), i);
- //fill List with ordered users
- allChatUsersListOrdered = Collections.synchronizedList(new ArrayList());
- for (Entry<String, Long> entry : userList) {
- if (allChatUsersMap.containsKey(entry.getKey())) {
- allChatUsersListOrdered.add(allChatUsersMap.get(entry.getKey()));
- }
- }
- Logger.debug(getClass(), "update adapter only now!");
- safeClose(mProgressDialog);
- // if (adapter != null) {
- // adapter.notifyDataSetChanged();
- // }
- ListUsersActivity.this.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- allChatUsersList.clear();
- allChatUsersList.addAll(allChatUsersListOrdered);
- if (adapter != null) {
- adapter.notifyDataSetChanged();
- }
- }
- });
- }
- // private class ReceiverThread extends Thread {
- // @Override
- // public void run() {
- // ListUsersActivity.this.runOnUiThread(new Runnable() {
- //
- // @Override
- // public void run() {
- // adapter.notifyDataSetChanged();
- // }
- // });
- // }
- @Override
- public void onChatUserClicked(String userId) {
- startUserActivity(this, userId);
- }
- @Override
- public void onChatUserProfileClicked(String userId) {
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.button_back:
- onBackPressed();
- break;
- case R.id.btnSendComment:
- if(validateSendComment()){
- ChatManager.getInstance().sendMessage(userObjectId, editTextMessage.getText().toString());
- }
- break;
- }
- }
- private boolean validateSendComment() {
- boolean result = false;
- boolean isTextWhitespace = editTextMessage.getText().toString().matches(Constants.WHITE_SPACES);
- if(userObjectId == null){
- Dialogs.showSingleButtonDialog(this, getString(R.string.pickUserError));
- } else if (isEmpty(editTextMessage.getText()) || isTextWhitespace) {
- Dialogs.showSingleButtonDialog(this, getString(R.string.emptyMessageError));
- } else {
- result = true;
- }
- return result;
- }
- private class MyServiceConnection implements ServiceConnection {
- @Override
- public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
- messageService = (MessageService.MessageServiceInterface) iBinder;
- messageService.addMessageClientListener(messageClientListener);
- }
- @Override
- public void onServiceDisconnected(ComponentName componentName) {
- messageService = null;
- }
- }
- private class MyMessageClientListener implements MessageClientListener {
- @Override
- public void onMessageFailed(MessageClient client, com.sinch.android.rtc.messaging.Message message,
- MessageFailureInfo failureInfo) {
- }
- @Override
- public void onIncomingMessage(MessageClient client, com.sinch.android.rtc.messaging.Message message) {
- Logger.debug(getClass(), "onIncomingMessage");
- getAllUsers();
- }
- @Override
- public void onMessageSent(MessageClient client, com.sinch.android.rtc.messaging.Message message, String recipientId) {
- Logger.debug(getClass(), "message to send: " + message.getTextBody());
- editTextMessage.setText("");
- for(UserProfile userProfile: allChatUsersList){
- if(userProfile.getId().equals(serverUserId)){
- getPointsOfCurrentUser(userProfile);
- }
- }
- }
- @Override
- public void onMessageDelivered(MessageClient client, MessageDeliveryInfo deliveryInfo) {
- }
- @Override
- public void onShouldSendPushData(MessageClient client, com.sinch.android.rtc.messaging.Message message, List<PushPair> pushPairs) {
- }
- }
- @Override
- public void onDestroy() {
- if (messageService != null) {
- messageService.removeMessageClientListener(messageClientListener);
- }
- // if(serviceConnection!=null){
- if (currentUser != null) {
- unbindService(serviceConnection);
- }
- // }
- super.onDestroy();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement