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.os.AsyncTask;
- 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.observer.IObserver;
- 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.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.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.List;
- import java.util.Map;
- import java.util.Set;
- import java.util.TreeMap;
- import static android.text.TextUtils.isEmpty;
- import static com.gfl.linewise.helpers.Intents.startUserActivity;
- public class ListUsersActivity extends CustomTitleActivity
- implements ListUsersAdapter.OnChatUserClickListener, View.OnClickListener, ChatManager.OnChatManagerEvent, MessageService.OnSinchClientCallback, IObserver<List<UserProfile>> {
- private ListView usersListView;
- private List<UserProfile> allUsersServerResponseList = new ArrayList<>();
- private List<UserProfile> allChatUsersList = new ArrayList<>();
- private List<UserProfile> allChatUsersListTemp = Collections.synchronizedList(new ArrayList<UserProfile>());
- // Set<UserProfile> allChatUsersListTemp = Collections.synchronizedSet(new TreeSet<UserProfile>());
- private Map<String, Message> firstUserMessages = Collections.synchronizedMap(new TreeMap<String, Message>());
- private ListUsersAdapter adapter;
- private MessageService.MessageServiceInterface messageService;
- private android.content.ServiceConnection serviceConnection = new ServiceConnection();
- private com.sinch.android.rtc.messaging.MessageClientListener messageClientListener = new MessageClientListener();
- private Map<String, String> allChatUsers = Collections.synchronizedMap(new TreeMap<String, String>());
- private UserSpinnerAdapter userSpinnerAdapter;
- private ParseUser currentUser;
- private String userObjectId;
- private String serverUserId;
- private EditText editTextMessage;
- // private List<UserProfile> allChatUsersListOrdered = Collections.synchronizedList(new ArrayList<UserProfile>());
- private List<UserProfile> allChatUsersListOrdered = new ArrayList<UserProfile>();
- private Button btnSendComment;
- // private ChatManager chatManager;
- private UserDownloaderAsyncTask userDownloaderAsyncTask;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_list_users);
- Logger.debug(getClass(), "ListUsersActivity onCreate");
- // chatManager = new ChatManager(this);
- Intent serviceIntent = new Intent(getApplicationContext(), MessageService.class);
- // startService(serviceIntent);
- currentUser = ParseUser.getCurrentUser();
- if (currentUser != null) {
- bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE);
- } else {
- Logger.debug(getClass(), "currentUser == null");
- }
- 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);
- btnSendComment = (Button) findViewById(R.id.btnSendComment);
- btnSendComment.setOnClickListener(this);
- // getAllUsers();
- // ChatManager.getInstance().bindService(this);
- }
- private void getPointsOfCurrentUser(final UserProfile userProfile) {
- Logger.debug(getClass(), "getPointsOfCurrentUser");
- 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) {
- Logger.debug(getClass(), "startChatWithUser");
- 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);
- Logger.debug(getClass(), "error loading User List");
- // Toast.makeText(getApplicationContext(),
- // "Error loading user list",
- // Toast.LENGTH_LONG).show();
- }
- }
- });
- }
- @Override
- public void onResume() {
- super.onResume();
- Logger.debug(getClass(), "ListUsersActivity onResume");
- setTitle(getString(R.string.title_activity_messaging));
- // if(messageClientListener == null){
- // messageClientListener = new MessageClientListener();
- // }
- // serviceConnection = new ServiceConnection();
- // messageService.addMessageClientListener(messageClientListener);
- // AllServerUsersManager.get().registerObserver(this);
- // getAllUsers();
- userDownloaderAsyncTask = new UserDownloaderAsyncTask();
- userDownloaderAsyncTask.execute();
- }
- @Override
- protected void onPause() {
- super.onPause();
- Logger.debug(getClass(), "ListUsersActivity onPause");
- Logger.debug(getClass(), "ListUsersActivity onPause finish");
- }
- 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. Try again later.",
- Toast.LENGTH_LONG).show();
- }
- }
- };
- LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter
- ("com.gfl.linewise.chat.ui.ListUsersActivity"));
- }
- public void getAllUsers() {
- Logger.debug(getClass(), "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) {
- Logger.debug(getClass(), "get chatUserFriends");
- 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");
- }
- }
- } else {
- Logger.debug(getClass(), "profiles == 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) {
- Logger.debug(getClass(), "getAllChatUsers: OK");
- Logger.debug(getClass(), "getAllChatUsers: size " + userList.size());
- for (int i = 0; i < userList.size(); i++) {
- allChatUsers.put(userList.get(i).getUsername(), userList.get(i).getObjectId());
- }
- initializeSendMessageSection();
- } else {
- Logger.debug(getClass(), "Error loading user list");
- }
- }
- });
- }
- private void initializeSendMessageSection() {
- //convert allUsersServerResponseList into allUsersServerResponseMap <Email, UserProfile>
- Map<String, UserProfile> allUsersServerResponseMap = new TreeMap<>();
- 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 (Map.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) {
- }
- });
- }
- @Override
- public void onIncomingMessageCallback(String textBody, String senderId) {
- }
- @Override
- public void onSinchClientStarted() {
- }
- 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");
- } else {
- Logger.error(getClass(), "Chat: unknown error, debug");
- }
- safeClose(mProgressDialog);
- }
- }
- @Override
- public void onChatUsersFound(final Map<String, ChatUser> chatUserFriends) {
- Logger.debug(getClass(), "ListUsersActivity onChatUsersFound");
- getChatUsersFromServerUsers(chatUserFriends);
- // ChatManager.getInstance().calculateUnreadMessages(chatUserFriends);
- }
- }
- private synchronized void getChatUsersFromServerUsers(final Map<String, ChatUser> chatUserFriends) {
- Logger.debug(getClass(), "getChatUsersFromServerUsers");
- Logger.debug(getClass(), "chatFriends size " + chatUserFriends.size());
- if (chatUserFriends.size() == 0) {
- adapter.notifyDataSetChanged();
- return;
- }
- for (Map.Entry<String, ChatUser> entry : chatUserFriends.entrySet()) {
- String key = entry.getKey();
- ChatUser value = entry.getValue();
- Logger.debug(getClass(), "chatUserFromServer key: " + key);
- Logger.debug(getClass(), "chatUserFromServer getSenderId: " + value.getSenderId());
- Logger.debug(getClass(), "chatUserFromServer getMessagesAmount: " + value.getMessagesAmount());
- // if(allUsersServerResponseList)
- iterateAllChatUsers(key, chatUserFriends.size());
- }
- }
- private synchronized void iterateAllChatUsers(final String senderId, final int friendsSize) {
- Logger.debug(getClass(), "iterateAllChatUsers");
- Map<String, String> foundKeysWithUsers = Collections.synchronizedMap(new TreeMap<String, String>());
- 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())) {
- allChatUsersListTemp.add(userProfile);
- foundKeysWithUsers.put(key, userProfile.getId());
- }
- }
- }
- for (Map.Entry<String, String> entry : foundKeysWithUsers.entrySet()) {
- getLastMessageByUser(entry.getKey(), entry.getValue(), friendsSize);
- }
- Logger.debug(getClass(), "iterateAllChatUsers end");
- }
- private synchronized void getLastMessageByUser(final String senderId, final String userId, final int friendsSize) {
- Logger.debug(getClass(), "getLastMessageByUser");
- final String currentUserId = currentUser.getObjectId();
- String[] userIds = {currentUserId, senderId};
- Logger.debug(getClass(), "currentUserId " + currentUserId);
- Logger.debug(getClass(), "senderId " + 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 synchronized void orderChatUsersByMessages() {
- Logger.debug(getClass(), "orderChatUsersByMessages");
- //create map with userId and Message object
- Map<String, Long> userMessageDateMap = new TreeMap<>();
- for (Map.Entry<String, Message> entry : firstUserMessages.entrySet()) {
- long createdMillis = entry.getValue().getCreatedAt();
- userMessageDateMap.put(entry.getKey(), createdMillis);
- }
- Set<Map.Entry<String, Long>> userSet = userMessageDateMap.entrySet();
- //get ordered list with user Id's by time of created message
- List<Map.Entry<String, Long>> userList = new ArrayList<>(userSet);
- Collections.sort(userList, new Comparator<Map.Entry<String, Long>>() {
- public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
- return (o2.getValue()).compareTo(o1.getValue());
- }
- });
- //convert allChatUsersList into allChatUsersMap
- Map<String, UserProfile> allChatUsersMap = new TreeMap<>();
- for (UserProfile i : allChatUsersListTemp) allChatUsersMap.put(i.getId(), i);
- //fill List with ordered users
- // allChatUsersListOrdered = new ArrayList<>();
- allChatUsersListOrdered.clear();
- for (Map.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);
- allChatUsersList.clear();
- allChatUsersList.addAll(allChatUsersListOrdered);
- if (adapter != null) {
- adapter.notifyDataSetChanged();
- }
- ListUsersActivity.this.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- }
- });
- }
- @Override
- public void onChatUserClicked(String userId) {
- startUserActivity(this, userId);
- }
- @Override
- public void onChatUserProfileClicked(String userId) {
- }
- @Override
- public void onClick(View v) {
- if (v == buttonBack) {
- onBackPressed();
- } else if (v == btnSendComment) {
- if (validateSendComment()) {
- // chatManager.sendMessage(userObjectId, editTextMessage.getText().toString());
- mProgressDialog.show();
- messageService.sendMessage(userObjectId, editTextMessage.getText().toString());
- }
- }
- }
- 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 ServiceConnection implements android.content.ServiceConnection {
- @Override
- public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
- messageService = (MessageService.MessageServiceInterface) iBinder;
- messageService.addMessageClientListener(messageClientListener, ListUsersActivity.this);
- }
- @Override
- public void onServiceDisconnected(ComponentName componentName) {
- messageService = null;
- }
- }
- private class MessageClientListener implements com.sinch.android.rtc.messaging.MessageClientListener {
- @Override
- public void onMessageFailed(MessageClient client, com.sinch.android.rtc.messaging.Message message,
- MessageFailureInfo failureInfo) {
- Logger.error(getClass(), "onMessageFailed");
- Logger.error(getClass(), "onMessageFailed error: " + failureInfo.getSinchError().getMessage());
- }
- @Override
- public void onIncomingMessage(MessageClient client, com.sinch.android.rtc.messaging.Message message) {
- Logger.debug(getClass(), "ListUsersActivity onIncomingMessage");
- // getAllUsers();
- // String senderId = message.getSenderId();
- ChatManager chatManager = new ChatManager();
- chatManager.saveUserInChatFriendList(message.getSenderId());
- userDownloaderAsyncTask = new UserDownloaderAsyncTask();
- userDownloaderAsyncTask.execute();
- }
- @Override
- public void onMessageSent(MessageClient client, com.sinch.android.rtc.messaging.Message message, String recipientId) {
- Logger.debug(getClass(), "ListUsersActivity onMessageSent: " + message.getTextBody());
- editTextMessage.setText("");
- // ChatManager chatManager = new ChatManager();
- // chatManager.saveUserInChatFriendList(recipientId);
- final ParseUser currentUser = ParseUser.getCurrentUser();
- if (currentUser != null) {
- final WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0),
- message.getTextBody());
- //only add message to parse database if it doesn't already exist there
- ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
- query.setLimit(1000);
- query.whereEqualTo("sinchId", message.getMessageId());
- query.findInBackground(new FindCallback<ParseObject>() {
- @Override
- public void done(List<ParseObject> messageList, com.parse.ParseException e) {
- if (e == null) {
- if (messageList.size() == 0) {
- ParseObject parseMessage = new ParseObject("ParseMessage");
- parseMessage.put("senderId", currentUser.getObjectId());
- parseMessage.put("recipientId", writableMessage.getRecipientIds().get(0));
- parseMessage.put("messageText", writableMessage.getTextBody());
- parseMessage.put("sinchId", writableMessage.getMessageId());
- parseMessage.saveInBackground();
- }
- }
- }
- });
- }
- Logger.debug(getClass(), "getPointsOfCurrentUser...");
- Logger.debug(getClass(), "allUsersServerResponseList size " + allUsersServerResponseList.size());
- for (UserProfile userProfile : allUsersServerResponseList) {
- if (userProfile.getId().equals(serverUserId)) {
- Logger.debug(getClass(), "getPointsOfCurrentUser...");
- getPointsOfCurrentUser(userProfile);
- }
- }
- mProgressDialog.show();
- // ChatManager.getInstance().saveUserInChatFriendList(recipientId);
- ChatManager chatManager = new ChatManager();
- chatManager.saveUserInChatFriendList(recipientId);
- }
- @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() {
- Logger.debug(getClass(), "ListUsersActivity onDestroy");
- if (messageService != null) {
- messageService.removeMessageClientListener(messageClientListener);
- }
- // if(serviceConnection!=null){
- ParseUser currentUser = ParseUser.getCurrentUser();
- if (currentUser != null) {
- unbindService(serviceConnection);
- }
- // }
- super.onDestroy();
- }
- @Override
- public void onObserved(List<UserProfile> userProfiles) {
- if (userProfiles != null) {
- allUsersServerResponseList.clear();
- allUsersServerResponseList.addAll(userProfiles);
- //to initialize send message layout
- // getAllChatUsers();
- if (currentUser != null) {
- Logger.debug(getClass(), "get chatUserFriends");
- 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");
- }
- } else {
- Logger.debug(getClass(), "profiles == null");
- }
- }
- @Override
- public void onNothing(IError error) {
- }
- private synchronized void getLastMessages(final String senderId, final String userId, final int friendsSize) {
- Logger.debug(getClass(), "getLastMessageByUser");
- final String currentUserId = currentUser.getObjectId();
- String[] userIds = {currentUserId, senderId};
- Logger.debug(getClass(), "currentUserId " + currentUserId);
- Logger.debug(getClass(), "senderId " + 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();
- }
- }
- }
- });
- }
- class UserDownloaderAsyncTask extends AsyncTask<Void, Void, Void> {
- @Override
- protected Void doInBackground(Void... params) {
- Logger.debug(getClass(), "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) {
- if (currentUser != null) {
- String currentUserId = ParseUser.getCurrentUser().getObjectId();
- ParseQuery<ParseObject> query = ParseQuery.getQuery(ChatManager.CHAT_USER_FRIENDS);
- try {
- int friendsSize;
- boolean isLastMessagesNeeded = true;
- //get chat users
- ParseObject parseObject = query.get(currentUser.get("chatUserObjectId").toString());
- 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());
- friendsSize = chatUsers.getChatUsers().size();
- //getAllChatUsers
- ParseQuery<ParseUser> allChatUsersQuery = ParseUser.getQuery();
- allChatUsersQuery.setLimit(1000);
- allChatUsersQuery.whereNotEqualTo("objectId", currentUserId);
- List<ParseUser> userList = allChatUsersQuery.find();
- Logger.debug(getClass(), "getAllChatUsers: size " + userList.size());
- for (int i = 0; i < userList.size(); i++) {
- allChatUsers.put(userList.get(i).getUsername(), userList.get(i).getObjectId());
- }
- initializeSendMessageSection();
- for (Map.Entry<String, ChatUser> entry : chatUsers.getChatUsers().entrySet()) {
- String chatUserKey = entry.getKey();
- ChatUser chatUserValue = entry.getValue();
- Logger.debug(getClass(), "chatUser key " + chatUserKey);
- Logger.debug(getClass(), "chatUser getSenderId: " + chatUserValue.getSenderId());
- Logger.debug(getClass(), "chatUser getMessagesAmount: " + chatUserValue.getMessagesAmount());
- if (isLastMessagesNeeded) {
- Map<String, String> foundKeysWithUsers = Collections.synchronizedMap(new TreeMap<String, String>());
- for (UserProfile userProfile : allUsersServerResponseList) {
- if (userProfile.getEmail().equals(chatUserValue.getUsername())) {
- Logger.debug(getClass(), "server users: chat user found " + userProfile.getEmail());
- allChatUsersListTemp.add(userProfile);
- foundKeysWithUsers.put(chatUserKey, userProfile.getId());
- //harder approach, gets messages, then order users by last message
- }
- }
- for (Map.Entry<String, String> userEntry : foundKeysWithUsers.entrySet()) {
- // getLastMessageByUser(userEntry.getKey(), userEntry.getValue(), friendsSize);
- Logger.debug(getClass(), "getLastMessageByUser");
- String[] userIds = {currentUserId, userEntry.getKey()};
- Logger.debug(getClass(), "currentUserId " + currentUserId);
- Logger.debug(getClass(), "senderId " + userEntry.getKey());
- ParseQuery<ParseObject> lastMessageQuery = ParseQuery.getQuery("ParseMessage");
- lastMessageQuery.whereContainedIn("senderId", Arrays.asList(userIds));
- lastMessageQuery.whereContainedIn("recipientId", Arrays.asList(userIds));
- lastMessageQuery.orderByDescending("createdAt");
- lastMessageQuery.setLimit(1);
- List<ParseObject> messageList = lastMessageQuery.find();
- 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(userEntry.getValue(), messageObj);
- }
- }
- }
- orderChatUsersByMessages();
- Logger.debug(getClass(), "chat: search finishing");
- Logger.debug(getClass(), "chat: search finished: chat: search finishing");
- } catch (ParseException e) {
- e.printStackTrace();
- }
- }
- }
- } else {
- Logger.debug(getClass(), "profiles == null");
- }
- }
- @Override
- public void onError(IError error) {
- Logger.error(getClass(), "GetAllUsersRequest error");
- safeClose(mProgressDialog);
- // showToast(ListUsersActivity.this, R.string.inet_problems);
- }
- }).execute();
- return null;
- }
- protected void onPostExecute(Void result) {
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement