Advertisement
Kvarz

works on my phone chat users

Sep 17th, 2015
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 38.32 KB | None | 0 0
  1. package com.gfl.linewise.chat.ui;
  2.  
  3. import android.content.BroadcastReceiver;
  4. import android.content.ComponentName;
  5. import android.content.Context;
  6. import android.content.Intent;
  7. import android.content.IntentFilter;
  8. import android.os.AsyncTask;
  9. import android.os.Bundle;
  10. import android.os.IBinder;
  11. import android.support.v4.content.LocalBroadcastManager;
  12. import android.view.View;
  13. import android.widget.AdapterView;
  14. import android.widget.Button;
  15. import android.widget.EditText;
  16. import android.widget.ListView;
  17. import android.widget.Spinner;
  18. import android.widget.Toast;
  19.  
  20. import com.alshvets.core.structure.helpers.Dialogs;
  21. import com.alshvets.core.structure.helpers.Logger;
  22. import com.alshvets.core.structure.models.error.IError;
  23. import com.alshvets.core.structure.observer.IObserver;
  24. import com.alshvets.core.structure.requests.mock.ICallback;
  25. import com.gfl.linewise.Constants;
  26. import com.gfl.linewise.R;
  27. import com.gfl.linewise.api.models.Session;
  28. import com.gfl.linewise.api.models.UserProfile;
  29. import com.gfl.linewise.api.models.responses.Profiles;
  30. import com.gfl.linewise.api.models.responses.UserInfo;
  31. import com.gfl.linewise.api.requests.GetAllUsersRequest;
  32. import com.gfl.linewise.api.requests.GetUserInfoRequest;
  33. import com.gfl.linewise.chat.ChatUsersSearch;
  34. import com.gfl.linewise.chat.MessageService;
  35. import com.gfl.linewise.chat.adapters.ListUsersAdapter;
  36. import com.gfl.linewise.chat.adapters.UserSpinnerAdapter;
  37. import com.gfl.linewise.chat.models.ChatUser;
  38. import com.gfl.linewise.chat.models.ChatUsers;
  39. import com.gfl.linewise.chat.models.Message;
  40. import com.gfl.linewise.chat.models.UserSpinner;
  41. import com.gfl.linewise.preferences.AppPreference;
  42. import com.gfl.linewise.ui.activities.CustomTitleActivity;
  43. import com.google.gson.Gson;
  44. import com.parse.FindCallback;
  45. import com.parse.GetCallback;
  46. import com.parse.ParseException;
  47. import com.parse.ParseObject;
  48. import com.parse.ParseQuery;
  49. import com.parse.ParseUser;
  50. import com.sinch.android.rtc.PushPair;
  51. import com.sinch.android.rtc.messaging.MessageClient;
  52. import com.sinch.android.rtc.messaging.MessageDeliveryInfo;
  53. import com.sinch.android.rtc.messaging.MessageFailureInfo;
  54. import com.sinch.android.rtc.messaging.WritableMessage;
  55.  
  56. import java.util.ArrayList;
  57. import java.util.Arrays;
  58. import java.util.Collections;
  59. import java.util.Comparator;
  60. import java.util.Date;
  61. import java.util.List;
  62. import java.util.Map;
  63. import java.util.Set;
  64. import java.util.TreeMap;
  65.  
  66. import static android.text.TextUtils.isEmpty;
  67. import static com.gfl.linewise.helpers.Intents.startUserActivity;
  68.  
  69. public class ListUsersActivity extends CustomTitleActivity
  70.         implements ListUsersAdapter.OnChatUserClickListener, View.OnClickListener, ChatManager.OnChatManagerEvent, MessageService.OnSinchClientCallback, IObserver<List<UserProfile>> {
  71.  
  72.  
  73.     private ListView usersListView;
  74.  
  75.     private List<UserProfile> allUsersServerResponseList = new ArrayList<>();
  76.     private List<UserProfile> allChatUsersList = new ArrayList<>();
  77.     private List<UserProfile> allChatUsersListTemp = Collections.synchronizedList(new ArrayList<UserProfile>());
  78.  
  79. //    Set<UserProfile> allChatUsersListTemp = Collections.synchronizedSet(new TreeSet<UserProfile>());
  80.  
  81.     private Map<String, Message> firstUserMessages = Collections.synchronizedMap(new TreeMap<String, Message>());
  82.     private ListUsersAdapter adapter;
  83.  
  84.     private MessageService.MessageServiceInterface messageService;
  85.     private android.content.ServiceConnection serviceConnection = new ServiceConnection();
  86.     private com.sinch.android.rtc.messaging.MessageClientListener messageClientListener = new MessageClientListener();
  87.  
  88.     private Map<String, String> allChatUsers = Collections.synchronizedMap(new TreeMap<String, String>());
  89.  
  90.     private UserSpinnerAdapter userSpinnerAdapter;
  91.  
  92.     private ParseUser currentUser;
  93.  
  94.     private String userObjectId;
  95.     private String serverUserId;
  96.  
  97.     private EditText editTextMessage;
  98.  
  99.     //    private List<UserProfile> allChatUsersListOrdered = Collections.synchronizedList(new ArrayList<UserProfile>());
  100.     private List<UserProfile> allChatUsersListOrdered = new ArrayList<UserProfile>();
  101.     private Button btnSendComment;
  102.  
  103. //    private ChatManager chatManager;
  104.  
  105.     private UserDownloaderAsyncTask userDownloaderAsyncTask;
  106.  
  107.  
  108.     @Override
  109.     protected void onCreate(Bundle savedInstanceState) {
  110.         super.onCreate(savedInstanceState);
  111.         setContentView(R.layout.activity_list_users);
  112.         Logger.debug(getClass(), "ListUsersActivity onCreate");
  113.  
  114. //        chatManager = new ChatManager(this);
  115.         Intent serviceIntent = new Intent(getApplicationContext(), MessageService.class);
  116. //        startService(serviceIntent);
  117.  
  118.         currentUser = ParseUser.getCurrentUser();
  119.         if (currentUser != null) {
  120.             bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE);
  121.  
  122.         } else {
  123.             Logger.debug(getClass(), "currentUser == null");
  124.         }
  125.  
  126.  
  127.         mProgressDialog.show();
  128.         mProgressDialog.setCancelable(true);
  129.  
  130.         registerBroadcastReceiver();
  131.  
  132.         buttonBack = findViewById(R.id.button_back);
  133.         buttonBack.setOnClickListener(this);
  134.  
  135.         usersListView = (ListView) findViewById(R.id.usersListView);
  136.  
  137.         adapter = new ListUsersAdapter(this, this, allChatUsersList, firstUserMessages);
  138.         usersListView.setAdapter(adapter);
  139.         usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  140.             @Override
  141.             public void onItemClick(AdapterView<?> a, View v, int i, long l) {
  142. //                startChatWithUser();
  143.                 getPointsOfCurrentUser(allChatUsersList.get(i));
  144.             }
  145.         });
  146.  
  147.         editTextMessage = (EditText) findViewById(R.id.editTextMessage);
  148.         btnSendComment = (Button) findViewById(R.id.btnSendComment);
  149.         btnSendComment.setOnClickListener(this);
  150.  
  151. //        getAllUsers();
  152. //        ChatManager.getInstance().bindService(this);
  153.     }
  154.  
  155.     private void getPointsOfCurrentUser(final UserProfile userProfile) {
  156.         Logger.debug(getClass(), "getPointsOfCurrentUser");
  157.         Session session = new Session(AppPreference.getInstance().getSession());
  158.  
  159.         new GetUserInfoRequest(session, new ICallback<UserInfo>() {
  160.             @Override
  161.             public void onSuccess(UserInfo userInfo) {
  162.                 Logger.debug(getClass(), "GetUserInfoRequest: OK");
  163.                 if (userInfo != null) {
  164. //                    updateUserInfo(userInfo);
  165.                     AppPreference.getInstance().setUserInfoResponse(new Gson().toJson(userInfo));
  166.                     startChatWithUser(userProfile);
  167.                 }
  168.             }
  169.  
  170.             @Override
  171.             public void onError(IError error) {
  172.                 Logger.error(getClass(), "GetUserInfoRequest error");
  173.             }
  174.         }).execute();
  175.     }
  176.  
  177.     private void startChatWithUser(final UserProfile userProfile) {
  178.         Logger.debug(getClass(), "startChatWithUser");
  179.         String username = userProfile.getEmail();
  180.         ParseQuery<ParseUser> query = ParseUser.getQuery();
  181.         query.setLimit(1000);
  182.         query.whereEqualTo("username", username);
  183.         query.findInBackground(new FindCallback<ParseUser>() {
  184.  
  185.             @Override
  186.             public void done(List<ParseUser> userList, ParseException e) {
  187.                 if (e == null) {
  188.                     //start the messaging activity
  189.                     Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
  190.                     intent.putExtra(MessagingActivity.RECIPIENT_ID, userList.get(0).getObjectId());
  191.                     intent.putExtra(MessagingActivity.USER_ID, userProfile.getId());
  192. //                    intent.putExtra(MessagingActivity.POINTS, points);
  193.                     intent.putExtra(MessagingActivity.PHOTO_URL, userProfile.getPhoto());
  194.                     startActivity(intent);
  195.                 } else {
  196.                     safeClose(mProgressDialog);
  197.                     Logger.debug(getClass(), "error loading User List");
  198. //                    Toast.makeText(getApplicationContext(),
  199. //                            "Error loading user list",
  200. //                            Toast.LENGTH_LONG).show();
  201.                 }
  202.             }
  203.         });
  204.     }
  205.  
  206.     @Override
  207.     public void onResume() {
  208.         super.onResume();
  209.         Logger.debug(getClass(), "ListUsersActivity onResume");
  210.         setTitle(getString(R.string.title_activity_messaging));
  211. //        if(messageClientListener == null){
  212. //            messageClientListener = new MessageClientListener();
  213. //        }
  214. //        serviceConnection = new ServiceConnection();
  215. //        messageService.addMessageClientListener(messageClientListener);
  216.  
  217. //        AllServerUsersManager.get().registerObserver(this);
  218.  
  219. //        getAllUsers();
  220.  
  221.         userDownloaderAsyncTask = new UserDownloaderAsyncTask();
  222.         userDownloaderAsyncTask.execute();
  223.  
  224.     }
  225.  
  226.     @Override
  227.     protected void onPause() {
  228.         super.onPause();
  229.         Logger.debug(getClass(), "ListUsersActivity onPause");
  230.         Logger.debug(getClass(), "ListUsersActivity onPause finish");
  231.     }
  232.  
  233.     private void registerBroadcastReceiver() {
  234.         BroadcastReceiver receiver = new BroadcastReceiver() {
  235.             @Override
  236.             public void onReceive(Context context, Intent intent) {
  237.                 Boolean success = intent.getBooleanExtra("success", false);
  238.                 if (!success) {
  239.                     safeClose(mProgressDialog);
  240.                     Toast.makeText(getApplicationContext(), "Sorry, messaging service not working. Try again later.",
  241.                             Toast.LENGTH_LONG).show();
  242.                 }
  243.             }
  244.         };
  245.  
  246.         LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter
  247.                 ("com.gfl.linewise.chat.ui.ListUsersActivity"));
  248.     }
  249.  
  250.     public void getAllUsers() {
  251.         Logger.debug(getClass(), "getAllUsers");
  252.         Session session = new Session(AppPreference.getInstance().getSession());
  253.  
  254.         new GetAllUsersRequest(session, new ICallback<Profiles>() {
  255.             @Override
  256.             public void onSuccess(Profiles profiles) {
  257.                 Logger.debug(getClass(), "GetAllUsersRequest: All users received");
  258.  
  259.                 if (profiles != null) {
  260.                     allUsersServerResponseList = profiles.getProfiles();
  261.                     if (allUsersServerResponseList != null) {
  262.  
  263.                         //to initialize send message layout
  264.                         getAllChatUsers();
  265.  
  266.                         if (currentUser != null) {
  267.                             Logger.debug(getClass(), "get chatUserFriends");
  268.                             ParseQuery<ParseObject> query = ParseQuery.getQuery(ChatManager.CHAT_USER_FRIENDS);
  269.                             query.getInBackground(currentUser.get("chatUserObjectId").toString(), new GetChatUserListCallback());
  270.                         } else {
  271.                             safeClose(mProgressDialog);
  272.                             Logger.debug(getClass(), "currentUser == null");
  273.                         }
  274.                     }
  275.                 } else {
  276.                     Logger.debug(getClass(), "profiles == null");
  277.                 }
  278.             }
  279.  
  280.             @Override
  281.             public void onError(IError error) {
  282.                 Logger.error(getClass(), "GetAllUsersRequest error");
  283.                 safeClose(mProgressDialog);
  284. //                showToast(ListUsersActivity.this, R.string.inet_problems);
  285.             }
  286.         }).execute();
  287.     }
  288.  
  289.     private void getAllChatUsers() {
  290.         String currentUserId = "";
  291.         if (ParseUser.getCurrentUser() != null) {
  292.             currentUserId = ParseUser.getCurrentUser().getObjectId();
  293.         } else {
  294.             return;
  295.         }
  296.  
  297.         //don't include yourself in the list
  298.         ParseQuery<ParseUser> query = ParseUser.getQuery();
  299.         query.setLimit(1000);
  300.         query.whereNotEqualTo("objectId", currentUserId);
  301.         query.findInBackground(new FindCallback<ParseUser>() {
  302.             public void done(List<ParseUser> userList, ParseException e) {
  303.                 if (e == null) {
  304.                     Logger.debug(getClass(), "getAllChatUsers: OK");
  305.                     Logger.debug(getClass(), "getAllChatUsers: size " + userList.size());
  306.                     for (int i = 0; i < userList.size(); i++) {
  307.                         allChatUsers.put(userList.get(i).getUsername(), userList.get(i).getObjectId());
  308.                     }
  309.                     initializeSendMessageSection();
  310.  
  311.                 } else {
  312.                     Logger.debug(getClass(), "Error loading user list");
  313.                 }
  314.             }
  315.         });
  316.     }
  317.  
  318.     private void initializeSendMessageSection() {
  319.  
  320.         //convert allUsersServerResponseList into allUsersServerResponseMap <Email, UserProfile>
  321.         Map<String, UserProfile> allUsersServerResponseMap = new TreeMap<>();
  322.         for (UserProfile i : allUsersServerResponseList)
  323.             allUsersServerResponseMap.put(i.getEmail(), i);
  324.  
  325.         //all server users that have chat account Map<chat Object id, UserSpinner>
  326.         final List<UserSpinner> allUsersWithChat = new ArrayList<>();
  327.  
  328.         for (Map.Entry<String, UserProfile> entry : allUsersServerResponseMap.entrySet()) {
  329.             String key = entry.getKey();
  330.             UserProfile value = entry.getValue();
  331.  
  332.             if (allChatUsers.containsKey(key)) {
  333.                 String objectId = allChatUsers.get(key);
  334.                 UserSpinner userSpinner = new UserSpinner(objectId, key, value);
  335.                 allUsersWithChat.add(userSpinner);
  336.             }
  337.         }
  338.  
  339.         Logger.debug(getClass(), "initializing spinner adapter");
  340.         Spinner spinner = (Spinner) findViewById(R.id.usersSpinner);
  341.         userSpinnerAdapter = new UserSpinnerAdapter(this, allUsersWithChat);
  342.         spinner.setAdapter(userSpinnerAdapter);
  343.         spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  344.  
  345.             @Override
  346.             public void onItemSelected(AdapterView<?> parent, View view,
  347.                                        int pos, long id) {
  348.                 serverUserId = allUsersWithChat.get(pos).getUserProfile().getId();
  349.                 userObjectId = allUsersWithChat.get(pos).getObjectId();
  350.                 userSpinnerAdapter.notifyDataSetChanged();
  351.             }
  352.  
  353.             @Override
  354.             public void onNothingSelected(AdapterView<?> arg0) {
  355.             }
  356.         });
  357.  
  358.     }
  359.  
  360.     @Override
  361.     public void onIncomingMessageCallback(String textBody, String senderId) {
  362.  
  363.     }
  364.  
  365.     @Override
  366.     public void onSinchClientStarted() {
  367.  
  368.     }
  369.  
  370.     private class GetChatUserListCallback implements GetCallback<ParseObject>, ChatUsersSearch.OnChatUsersFoundListener {
  371.  
  372.         @Override
  373.         public void done(ParseObject parseObject, ParseException e) {
  374.             if (e == null) {
  375.                 Logger.debug(getClass(), "Chat: chat list object FOUND " + parseObject.getObjectId());
  376.  
  377.                 String jsonString = (String) parseObject.get("chatUsers");
  378.                 Logger.debug(getClass(), "chatUsers json! " + jsonString);
  379.                 ChatUsers chatUsers = new Gson().fromJson(jsonString, ChatUsers.class);
  380.  
  381.                 Logger.debug(getClass(), "CHAT FRIENDS SIZE: " + chatUsers.getChatUsers().size());
  382.  
  383.                 if (chatUsers.getChatUsers().size() > 0) {
  384.                     ChatUsersSearch chatUsersSearch = new ChatUsersSearch(this);
  385.                     chatUsersSearch.startSearch(chatUsers.getChatUsers());
  386.                 } else {
  387.                     safeClose(mProgressDialog);
  388.                 }
  389.  
  390.             } else {
  391.                 if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
  392.                     Logger.error(getClass(), "Chat: ParseException.OBJECT_NOT_FOUND");
  393.                 } else {
  394.                     Logger.error(getClass(), "Chat: unknown error, debug");
  395.                 }
  396.                 safeClose(mProgressDialog);
  397.             }
  398.         }
  399.  
  400.  
  401.         @Override
  402.         public void onChatUsersFound(final Map<String, ChatUser> chatUserFriends) {
  403.             Logger.debug(getClass(), "ListUsersActivity onChatUsersFound");
  404.             getChatUsersFromServerUsers(chatUserFriends);
  405. //            ChatManager.getInstance().calculateUnreadMessages(chatUserFriends);
  406.         }
  407.     }
  408.  
  409.     private synchronized void getChatUsersFromServerUsers(final Map<String, ChatUser> chatUserFriends) {
  410.  
  411.         Logger.debug(getClass(), "getChatUsersFromServerUsers");
  412.         Logger.debug(getClass(), "chatFriends size " + chatUserFriends.size());
  413.  
  414.         if (chatUserFriends.size() == 0) {
  415.             adapter.notifyDataSetChanged();
  416.             return;
  417.         }
  418.  
  419.         for (Map.Entry<String, ChatUser> entry : chatUserFriends.entrySet()) {
  420.             String key = entry.getKey();
  421.             ChatUser value = entry.getValue();
  422.             Logger.debug(getClass(), "chatUserFromServer key: " + key);
  423.             Logger.debug(getClass(), "chatUserFromServer getSenderId: " + value.getSenderId());
  424.             Logger.debug(getClass(), "chatUserFromServer getMessagesAmount: " + value.getMessagesAmount());
  425.  
  426. //            if(allUsersServerResponseList)
  427.             iterateAllChatUsers(key, chatUserFriends.size());
  428.         }
  429.     }
  430.  
  431.     private synchronized void iterateAllChatUsers(final String senderId, final int friendsSize) {
  432.         Logger.debug(getClass(), "iterateAllChatUsers");
  433.  
  434.         Map<String, String> foundKeysWithUsers = Collections.synchronizedMap(new TreeMap<String, String>());
  435.  
  436.  
  437.         for (Map.Entry<String, ChatUser> entry : ChatManager.getChatUsers().getChatUsers().entrySet()) {
  438.             String key = entry.getKey();
  439.             ChatUser value = entry.getValue();
  440.             Logger.debug(getClass(), "chatUser key" + key);
  441.             Logger.debug(getClass(), "chatUser getSenderId: " + value.getSenderId());
  442.             Logger.debug(getClass(), "chatUser getMessagesAmount: " + value.getMessagesAmount());
  443.  
  444.             Logger.debug(getClass(), "email of user!  " + value.getUsername());
  445.             for (UserProfile userProfile : allUsersServerResponseList) {
  446.                 if (userProfile.getEmail().equals(value.getUsername())) {
  447.                     allChatUsersListTemp.add(userProfile);
  448.                     foundKeysWithUsers.put(key, userProfile.getId());
  449.  
  450.                 }
  451.             }
  452.         }
  453.  
  454.         for (Map.Entry<String, String> entry : foundKeysWithUsers.entrySet()) {
  455.             getLastMessageByUser(entry.getKey(), entry.getValue(), friendsSize);
  456.         }
  457.  
  458.  
  459.         Logger.debug(getClass(), "iterateAllChatUsers end");
  460.     }
  461.  
  462.     private synchronized void getLastMessageByUser(final String senderId, final String userId, final int friendsSize) {
  463.         Logger.debug(getClass(), "getLastMessageByUser");
  464.         final String currentUserId = currentUser.getObjectId();
  465.         String[] userIds = {currentUserId, senderId};
  466.  
  467.         Logger.debug(getClass(), "currentUserId " + currentUserId);
  468.         Logger.debug(getClass(), "senderId " + senderId);
  469.  
  470.         ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
  471.         query.whereContainedIn("senderId", Arrays.asList(userIds));
  472.         query.whereContainedIn("recipientId", Arrays.asList(userIds));
  473.         query.orderByDescending("createdAt");
  474.         query.setLimit(1);
  475.         query.findInBackground(new FindCallback<ParseObject>() {
  476.             @Override
  477.             public void done(List<ParseObject> messageList, com.parse.ParseException e) {
  478.                 if (e == null) {
  479.                     WritableMessage message = new WritableMessage(messageList.get(0).get("recipientId").
  480.                             toString(), messageList.get(0).get("messageText").toString());
  481.  
  482.                     Date createdAt = messageList.get(0).getCreatedAt();
  483.                     long createdAtMilliseconds = createdAt.getTime();
  484.  
  485.                     Message messageObj = new Message(message.getTextBody(), createdAtMilliseconds);
  486.                     firstUserMessages.put(userId, messageObj);
  487.                     if (friendsSize <= firstUserMessages.size()) {
  488.                         orderChatUsersByMessages();
  489.                     }
  490.                 }
  491.             }
  492.         });
  493.     }
  494.  
  495.     private synchronized void orderChatUsersByMessages() {
  496.         Logger.debug(getClass(), "orderChatUsersByMessages");
  497.         //create map with userId and Message object
  498.         Map<String, Long> userMessageDateMap = new TreeMap<>();
  499.         for (Map.Entry<String, Message> entry : firstUserMessages.entrySet()) {
  500.             long createdMillis = entry.getValue().getCreatedAt();
  501.             userMessageDateMap.put(entry.getKey(), createdMillis);
  502.         }
  503.         Set<Map.Entry<String, Long>> userSet = userMessageDateMap.entrySet();
  504.  
  505.         //get ordered list with user Id's by time of created message
  506.         List<Map.Entry<String, Long>> userList = new ArrayList<>(userSet);
  507.         Collections.sort(userList, new Comparator<Map.Entry<String, Long>>() {
  508.             public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
  509.                 return (o2.getValue()).compareTo(o1.getValue());
  510.             }
  511.         });
  512.  
  513.         //convert allChatUsersList into allChatUsersMap
  514.         Map<String, UserProfile> allChatUsersMap = new TreeMap<>();
  515.         for (UserProfile i : allChatUsersListTemp) allChatUsersMap.put(i.getId(), i);
  516.  
  517.         //fill List with ordered users
  518.  
  519. //        allChatUsersListOrdered = new ArrayList<>();
  520.         allChatUsersListOrdered.clear();
  521.         for (Map.Entry<String, Long> entry : userList) {
  522.             if (allChatUsersMap.containsKey(entry.getKey())) {
  523.                 allChatUsersListOrdered.add(allChatUsersMap.get(entry.getKey()));
  524.             }
  525.         }
  526.  
  527.  
  528.         Logger.debug(getClass(), "update adapter only now!");
  529.         safeClose(mProgressDialog);
  530.  
  531.  
  532.         allChatUsersList.clear();
  533.         allChatUsersList.addAll(allChatUsersListOrdered);
  534.         if (adapter != null) {
  535.             adapter.notifyDataSetChanged();
  536.         }
  537.  
  538.         ListUsersActivity.this.runOnUiThread(new Runnable() {
  539.  
  540.             @Override
  541.             public void run() {
  542.  
  543.             }
  544.         });
  545.  
  546.  
  547.     }
  548.  
  549.     @Override
  550.     public void onChatUserClicked(String userId) {
  551.         startUserActivity(this, userId);
  552.     }
  553.  
  554.     @Override
  555.     public void onChatUserProfileClicked(String userId) {
  556.  
  557.     }
  558.  
  559.     @Override
  560.     public void onClick(View v) {
  561.         if (v == buttonBack) {
  562.             onBackPressed();
  563.         } else if (v == btnSendComment) {
  564.             if (validateSendComment()) {
  565. //                chatManager.sendMessage(userObjectId, editTextMessage.getText().toString());
  566.                 mProgressDialog.show();
  567.                 messageService.sendMessage(userObjectId, editTextMessage.getText().toString());
  568.             }
  569.         }
  570.     }
  571.  
  572.     private boolean validateSendComment() {
  573.         boolean result = false;
  574.         boolean isTextWhitespace = editTextMessage.getText().toString().matches(Constants.WHITE_SPACES);
  575.         if (userObjectId == null) {
  576.             Dialogs.showSingleButtonDialog(this, getString(R.string.pickUserError));
  577.         } else if (isEmpty(editTextMessage.getText()) || isTextWhitespace) {
  578.             Dialogs.showSingleButtonDialog(this, getString(R.string.emptyMessageError));
  579.         } else {
  580.             result = true;
  581.         }
  582.         return result;
  583.     }
  584.  
  585.     private class ServiceConnection implements android.content.ServiceConnection {
  586.         @Override
  587.         public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
  588.             messageService = (MessageService.MessageServiceInterface) iBinder;
  589.             messageService.addMessageClientListener(messageClientListener, ListUsersActivity.this);
  590.         }
  591.  
  592.         @Override
  593.         public void onServiceDisconnected(ComponentName componentName) {
  594.             messageService = null;
  595.         }
  596.     }
  597.  
  598.     private class MessageClientListener implements com.sinch.android.rtc.messaging.MessageClientListener {
  599.         @Override
  600.         public void onMessageFailed(MessageClient client, com.sinch.android.rtc.messaging.Message message,
  601.                                     MessageFailureInfo failureInfo) {
  602.             Logger.error(getClass(), "onMessageFailed");
  603.             Logger.error(getClass(), "onMessageFailed error: " + failureInfo.getSinchError().getMessage());
  604.         }
  605.  
  606.         @Override
  607.         public void onIncomingMessage(MessageClient client, com.sinch.android.rtc.messaging.Message message) {
  608.             Logger.debug(getClass(), "ListUsersActivity onIncomingMessage");
  609. //            getAllUsers();
  610. //            String senderId = message.getSenderId();
  611.             ChatManager chatManager = new ChatManager();
  612.             chatManager.saveUserInChatFriendList(message.getSenderId());
  613.  
  614.             userDownloaderAsyncTask = new UserDownloaderAsyncTask();
  615.             userDownloaderAsyncTask.execute();
  616.         }
  617.  
  618.  
  619.         @Override
  620.         public void onMessageSent(MessageClient client, com.sinch.android.rtc.messaging.Message message, String recipientId) {
  621.             Logger.debug(getClass(), "ListUsersActivity onMessageSent: " + message.getTextBody());
  622.             editTextMessage.setText("");
  623. //            ChatManager chatManager = new ChatManager();
  624. //            chatManager.saveUserInChatFriendList(recipientId);
  625.  
  626.             final ParseUser currentUser = ParseUser.getCurrentUser();
  627.             if (currentUser != null) {
  628.                 final WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0),
  629.                         message.getTextBody());
  630.  
  631.                 //only add message to parse database if it doesn't already exist there
  632.                 ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
  633.                 query.setLimit(1000);
  634.                 query.whereEqualTo("sinchId", message.getMessageId());
  635.                 query.findInBackground(new FindCallback<ParseObject>() {
  636.                     @Override
  637.                     public void done(List<ParseObject> messageList, com.parse.ParseException e) {
  638.                         if (e == null) {
  639.                             if (messageList.size() == 0) {
  640.                                 ParseObject parseMessage = new ParseObject("ParseMessage");
  641.                                 parseMessage.put("senderId", currentUser.getObjectId());
  642.                                 parseMessage.put("recipientId", writableMessage.getRecipientIds().get(0));
  643.                                 parseMessage.put("messageText", writableMessage.getTextBody());
  644.                                 parseMessage.put("sinchId", writableMessage.getMessageId());
  645.                                 parseMessage.saveInBackground();
  646.                             }
  647.                         }
  648.                     }
  649.                 });
  650.             }
  651.  
  652.             Logger.debug(getClass(), "getPointsOfCurrentUser...");
  653.             Logger.debug(getClass(), "allUsersServerResponseList size " + allUsersServerResponseList.size());
  654.             for (UserProfile userProfile : allUsersServerResponseList) {
  655.                 if (userProfile.getId().equals(serverUserId)) {
  656.                     Logger.debug(getClass(), "getPointsOfCurrentUser...");
  657.                     getPointsOfCurrentUser(userProfile);
  658.                 }
  659.             }
  660.  
  661.             mProgressDialog.show();
  662.  
  663. //            ChatManager.getInstance().saveUserInChatFriendList(recipientId);
  664.             ChatManager chatManager = new ChatManager();
  665.             chatManager.saveUserInChatFriendList(recipientId);
  666.  
  667.         }
  668.  
  669.         @Override
  670.         public void onMessageDelivered(MessageClient client, MessageDeliveryInfo deliveryInfo) {
  671.         }
  672.  
  673.         @Override
  674.         public void onShouldSendPushData(MessageClient client, com.sinch.android.rtc.messaging.Message message, List<PushPair> pushPairs) {
  675.         }
  676.     }
  677.  
  678.     @Override
  679.     public void onDestroy() {
  680.         Logger.debug(getClass(), "ListUsersActivity onDestroy");
  681.         if (messageService != null) {
  682.             messageService.removeMessageClientListener(messageClientListener);
  683.         }
  684. //        if(serviceConnection!=null){
  685.         ParseUser currentUser = ParseUser.getCurrentUser();
  686.         if (currentUser != null) {
  687.             unbindService(serviceConnection);
  688.         }
  689.  
  690. //        }
  691.         super.onDestroy();
  692.     }
  693.  
  694.     @Override
  695.     public void onObserved(List<UserProfile> userProfiles) {
  696.         if (userProfiles != null) {
  697.             allUsersServerResponseList.clear();
  698.             allUsersServerResponseList.addAll(userProfiles);
  699.  
  700.             //to initialize send message layout
  701. //            getAllChatUsers();
  702.  
  703.             if (currentUser != null) {
  704.                 Logger.debug(getClass(), "get chatUserFriends");
  705.                 ParseQuery<ParseObject> query = ParseQuery.getQuery(ChatManager.CHAT_USER_FRIENDS);
  706.                 query.getInBackground(currentUser.get("chatUserObjectId").toString(), new GetChatUserListCallback());
  707.             } else {
  708.                 safeClose(mProgressDialog);
  709.                 Logger.debug(getClass(), "currentUser == null");
  710.             }
  711.         } else {
  712.             Logger.debug(getClass(), "profiles == null");
  713.         }
  714.     }
  715.  
  716.     @Override
  717.     public void onNothing(IError error) {
  718.  
  719.     }
  720.  
  721.     private synchronized void getLastMessages(final String senderId, final String userId, final int friendsSize) {
  722.         Logger.debug(getClass(), "getLastMessageByUser");
  723.         final String currentUserId = currentUser.getObjectId();
  724.         String[] userIds = {currentUserId, senderId};
  725.  
  726.         Logger.debug(getClass(), "currentUserId " + currentUserId);
  727.         Logger.debug(getClass(), "senderId " + senderId);
  728.  
  729.         ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
  730.         query.whereContainedIn("senderId", Arrays.asList(userIds));
  731.         query.whereContainedIn("recipientId", Arrays.asList(userIds));
  732.         query.orderByDescending("createdAt");
  733.         query.setLimit(1);
  734.         query.findInBackground(new FindCallback<ParseObject>() {
  735.             @Override
  736.             public void done(List<ParseObject> messageList, com.parse.ParseException e) {
  737.                 if (e == null) {
  738.                     WritableMessage message = new WritableMessage(messageList.get(0).get("recipientId").
  739.                             toString(), messageList.get(0).get("messageText").toString());
  740.  
  741.                     Date createdAt = messageList.get(0).getCreatedAt();
  742.                     long createdAtMilliseconds = createdAt.getTime();
  743.  
  744.                     Message messageObj = new Message(message.getTextBody(), createdAtMilliseconds);
  745.                     firstUserMessages.put(userId, messageObj);
  746.  
  747.                     if (friendsSize <= firstUserMessages.size()) {
  748.                         orderChatUsersByMessages();
  749.                     }
  750.                 }
  751.             }
  752.         });
  753.     }
  754.  
  755.     class UserDownloaderAsyncTask extends AsyncTask<Void, Void, Void> {
  756.  
  757.         @Override
  758.         protected Void doInBackground(Void... params) {
  759.             Logger.debug(getClass(), "getAllUsers");
  760.             Session session = new Session(AppPreference.getInstance().getSession());
  761.  
  762.             new GetAllUsersRequest(session, new ICallback<Profiles>() {
  763.                 @Override
  764.                 public void onSuccess(Profiles profiles) {
  765.                     Logger.debug(getClass(), "GetAllUsersRequest: All users received");
  766.  
  767.                     if (profiles != null) {
  768.                         allUsersServerResponseList = profiles.getProfiles();
  769.                         if (allUsersServerResponseList != null) {
  770.  
  771.                             if (currentUser != null) {
  772.                                 String currentUserId = ParseUser.getCurrentUser().getObjectId();
  773.  
  774.  
  775.                                 ParseQuery<ParseObject> query = ParseQuery.getQuery(ChatManager.CHAT_USER_FRIENDS);
  776.                                 try {
  777.                                     int friendsSize;
  778.  
  779.                                     boolean isLastMessagesNeeded = true;
  780.  
  781.                                     //get chat users
  782.                                     ParseObject parseObject = query.get(currentUser.get("chatUserObjectId").toString());
  783.                                     String jsonString = (String) parseObject.get("chatUsers");
  784.  
  785.                                     Logger.debug(getClass(), "chatUsers json! " + jsonString);
  786.                                     ChatUsers chatUsers = new Gson().fromJson(jsonString, ChatUsers.class);
  787.                                     Logger.debug(getClass(), "CHAT FRIENDS SIZE: " + chatUsers.getChatUsers().size());
  788.  
  789.                                     friendsSize = chatUsers.getChatUsers().size();
  790.  
  791.                                     //getAllChatUsers
  792.                                     ParseQuery<ParseUser> allChatUsersQuery = ParseUser.getQuery();
  793.                                     allChatUsersQuery.setLimit(1000);
  794.                                     allChatUsersQuery.whereNotEqualTo("objectId", currentUserId);
  795.                                     List<ParseUser> userList = allChatUsersQuery.find();
  796.                                     Logger.debug(getClass(), "getAllChatUsers: size " + userList.size());
  797.  
  798.                                     for (int i = 0; i < userList.size(); i++) {
  799.                                         allChatUsers.put(userList.get(i).getUsername(), userList.get(i).getObjectId());
  800.                                     }
  801.  
  802.                                     initializeSendMessageSection();
  803.  
  804.  
  805.                                     for (Map.Entry<String, ChatUser> entry : chatUsers.getChatUsers().entrySet()) {
  806.                                         String chatUserKey = entry.getKey();
  807.                                         ChatUser chatUserValue = entry.getValue();
  808.                                         Logger.debug(getClass(), "chatUser key " + chatUserKey);
  809.                                         Logger.debug(getClass(), "chatUser getSenderId: " + chatUserValue.getSenderId());
  810.                                         Logger.debug(getClass(), "chatUser getMessagesAmount: " + chatUserValue.getMessagesAmount());
  811.  
  812.                                         if (isLastMessagesNeeded) {
  813.  
  814.                                             Map<String, String> foundKeysWithUsers = Collections.synchronizedMap(new TreeMap<String, String>());
  815.  
  816.  
  817.                                             for (UserProfile userProfile : allUsersServerResponseList) {
  818.                                                 if (userProfile.getEmail().equals(chatUserValue.getUsername())) {
  819.                                                     Logger.debug(getClass(), "server users: chat user found " + userProfile.getEmail());
  820.                                                     allChatUsersListTemp.add(userProfile);
  821.                                                     foundKeysWithUsers.put(chatUserKey, userProfile.getId());
  822.                                                     //harder approach, gets messages, then order users by last message
  823.  
  824.                                                 }
  825.                                             }
  826.  
  827.                                             for (Map.Entry<String, String> userEntry : foundKeysWithUsers.entrySet()) {
  828.  
  829. //                                                getLastMessageByUser(userEntry.getKey(), userEntry.getValue(), friendsSize);
  830.  
  831.                                                 Logger.debug(getClass(), "getLastMessageByUser");
  832.                                                 String[] userIds = {currentUserId, userEntry.getKey()};
  833.  
  834.                                                 Logger.debug(getClass(), "currentUserId " + currentUserId);
  835.                                                 Logger.debug(getClass(), "senderId " + userEntry.getKey());
  836.  
  837.                                                 ParseQuery<ParseObject> lastMessageQuery = ParseQuery.getQuery("ParseMessage");
  838.                                                 lastMessageQuery.whereContainedIn("senderId", Arrays.asList(userIds));
  839.                                                 lastMessageQuery.whereContainedIn("recipientId", Arrays.asList(userIds));
  840.                                                 lastMessageQuery.orderByDescending("createdAt");
  841.                                                 lastMessageQuery.setLimit(1);
  842.                                                 List<ParseObject> messageList = lastMessageQuery.find();
  843.  
  844.                                                 WritableMessage message = new WritableMessage(messageList.get(0).get("recipientId").
  845.                                                         toString(), messageList.get(0).get("messageText").toString());
  846.  
  847.                                                 Date createdAt = messageList.get(0).getCreatedAt();
  848.                                                 long createdAtMilliseconds = createdAt.getTime();
  849.  
  850.                                                 Message messageObj = new Message(message.getTextBody(), createdAtMilliseconds);
  851.                                                 firstUserMessages.put(userEntry.getValue(), messageObj);
  852.                                             }
  853.                                         }
  854.                                     }
  855.                                     orderChatUsersByMessages();
  856.  
  857.                                     Logger.debug(getClass(), "chat: search finishing");
  858.  
  859.                                     Logger.debug(getClass(), "chat: search finished: chat: search finishing");
  860.  
  861.                                 } catch (ParseException e) {
  862.                                     e.printStackTrace();
  863.                                 }
  864.  
  865.                             }
  866.  
  867.  
  868.                         }
  869.                     } else {
  870.                         Logger.debug(getClass(), "profiles == null");
  871.                     }
  872.                 }
  873.  
  874.                 @Override
  875.                 public void onError(IError error) {
  876.                     Logger.error(getClass(), "GetAllUsersRequest error");
  877.                     safeClose(mProgressDialog);
  878. //                showToast(ListUsersActivity.this, R.string.inet_problems);
  879.                 }
  880.             }).execute();
  881.             return null;
  882.         }
  883.  
  884.         protected void onPostExecute(Void result) {
  885.         }
  886.  
  887.     }
  888.  
  889. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement