Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.myplaylifeapp.android.myplaylife.Configuration;
- import android.app.AlertDialog;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.support.v4.content.LocalBroadcastManager;
- import android.util.Log;
- import com.android.volley.Response;
- import com.android.volley.error.VolleyError;
- import com.google.gson.Gson;
- import com.myplaylifeapp.android.myplaylife.CallbackListener;
- import com.myplaylifeapp.android.myplaylife.Interface.MainApp.UsersProfile.Memories.RecyclerView.MemoriesViewHolder;
- import com.myplaylifeapp.android.myplaylife.R;
- import com.myplaylifeapp.android.myplaylife.Realm.Objects.Friendship;
- import com.myplaylifeapp.android.myplaylife.Realm.Objects.Memory;
- import com.myplaylifeapp.android.myplaylife.Realm.Objects.MemoryEmotion;
- import com.myplaylifeapp.android.myplaylife.Realm.Objects.MemoryKeyword;
- import com.myplaylifeapp.android.myplaylife.Realm.Objects.MoodType;
- import com.myplaylifeapp.android.myplaylife.Realm.Objects.Notification;
- import com.myplaylifeapp.android.myplaylife.Realm.Objects.ReceivedInvite;
- import com.myplaylifeapp.android.myplaylife.Realm.Objects.RelationshipType;
- import com.myplaylifeapp.android.myplaylife.Realm.Objects.SentInvite;
- import com.myplaylifeapp.android.myplaylife.Realm.Objects.User;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.InvitesRequests.DeclineInvite;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.InvitesRequests.DeleteSentInvite;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.InvitesRequests.ReceivedInvites;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.InvitesRequests.SentInvites;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.KeywordsRequest;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.MoodsRequest;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.RelationshipTypesRequest;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyDeleteArrayRequest;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyDeleteRequest;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyGetArrayRequest;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyPostArrayRequest;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyPostRequest;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyPutRequest;
- import com.myplaylifeapp.android.myplaylife.VolleySingleton;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.TimeZone;
- import io.realm.Realm;
- import io.realm.RealmList;
- import io.realm.RealmResults;
- /**
- * Created by jack on 20/02/2018.
- */
- public class RequestOperations {
- private static final RequestOperations sharedInstance = new RequestOperations();
- public static RequestOperations getInstance() {
- return sharedInstance;
- }
- public void volleyErrorHandler(VolleyError error, final Context context) {
- if (error != null && error.networkResponse != null && error.networkResponse.data != null) {
- String errorString = "";
- if (error.networkResponse.statusCode == 401) {
- try {
- AlertDialog alertDialog = new AlertDialog.Builder(context).create();
- alertDialog.setCancelable(false);
- alertDialog.setTitle("Unauthorised");
- alertDialog.setMessage("You have been logged out of the application");
- alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- ConfigurationManager.getInstance().logout(context);
- }
- });
- alertDialog.show();
- } catch (Exception e) {
- ConfigurationManager.getInstance().logout(context);
- }
- }
- try {
- JSONObject jobj = new JSONObject(new String(error.networkResponse.data));
- JSONArray errorArray = jobj.getJSONArray("errors");
- for (int i = 0; i < errorArray.length(); i++) {
- Log.d("Volley Error", "" + errorArray.getString(i));
- errorString = errorString + errorArray.getString(i) + "\n";
- }
- } catch (JSONException exception) {
- Log.d("Error", "" + "Error");
- }
- try {
- AlertDialog alertDialog = new AlertDialog.Builder(context).create();
- alertDialog.setTitle("Error");
- alertDialog.setMessage(errorString);
- alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- alertDialog.show();
- } catch (Exception e) {
- e.printStackTrace();
- }
- } else {
- try {
- AlertDialog alertDialog = new AlertDialog.Builder(context).create();
- alertDialog.setTitle("Error");
- alertDialog.setMessage("Cant connect to server");
- alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- alertDialog.show();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public void checkAuthorisation(VolleyError error) {
- if (error != null && error.networkResponse != null && error.networkResponse.data != null) {
- if (error.networkResponse.statusCode == 401) {
- try {
- Log.e("VolleyError", error.toString());
- ConfigurationManager.getInstance().logout(AppDelegate.getAppContext());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- public void forgotPasswordRequest(final String emailAddress, final Context context) {
- String urlString = APIEndPoint.PASSWORD_RESETS.urlString();
- Map<String, Object> params = new HashMap();
- params.put("email", emailAddress);
- JSONObject jsonObject = new JSONObject(params);
- VolleyPostRequest forgotPasswordRequest = new VolleyPostRequest(urlString, jsonObject, new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context)
- .setTitle("Success")
- .setMessage(String.format("An email has been sent to %s with password reset instructions", emailAddress))
- .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- alertDialog.show();
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- volleyErrorHandler(error, context);
- }
- });
- VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(forgotPasswordRequest);
- }
- public void keywordsRequest() {
- KeywordsRequest keywordsRequest = new KeywordsRequest(new Response.Listener<JSONArray>() {
- @Override
- public void onResponse(JSONArray response) {
- Realm realm = Realm.getDefaultInstance();
- final Gson gson = new Gson();
- for (int i = 0; i < response.length(); i++) {
- try {
- final JSONObject keywordObject = response.getJSONObject(i);
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- final MemoryKeyword memoryKeyword = gson.fromJson(keywordObject.toString(), MemoryKeyword.class);
- if (memoryKeyword != null) {
- realm.insertOrUpdate(memoryKeyword);
- }
- }
- });
- } catch(JSONException exception) {
- Log.d("Keywords Response", "Failed to parse JSON object");
- }
- }
- realm.close();
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- checkAuthorisation(error);
- }
- });
- VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(keywordsRequest);
- }
- public void moodsRequest() {
- MoodsRequest moodsRequest = new MoodsRequest(new Response.Listener<JSONArray>() {
- @Override
- public void onResponse(JSONArray response) {
- Realm realm = Realm.getDefaultInstance();
- final Gson gson = new Gson();
- for (int i = 0; i < response.length(); i++) {
- try {
- final JSONObject moodObject = response.getJSONObject(i);
- if (moodObject != null) {
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- final MoodType moodType = gson.fromJson(moodObject.toString(), MoodType.class);
- if (moodType != null) {
- realm.insertOrUpdate(moodType);
- }
- }
- });
- }
- } catch(JSONException exception) {
- Log.d("Moods Response", "Failed to parse JSON object");
- }
- }
- realm.close();
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- checkAuthorisation(error);
- }
- });
- VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(moodsRequest);
- }
- public void friendsRequest(final int currentUserID, final int friendID, final CallbackListener callbackListener) {
- final Map<String, Object> urlParams = new HashMap<String, Object>();
- urlParams.put("userID", currentUserID);
- if (friendID != 0) {
- urlParams.put("friendID", friendID);
- }
- final String urlString = APIEndPoint.FRIENDS.urlString(urlParams);
- if (urlString == null) {
- Log.e("Error: ", "Cant construct url string");
- return;
- }
- VolleyGetArrayRequest friendsRequest = new VolleyGetArrayRequest(urlString, new Response.Listener<JSONArray>() {
- @Override
- public void onResponse(final JSONArray response) {
- new Thread(new Runnable() {
- public void run() {
- final Gson gson = new Gson();
- Realm realm = Realm.getDefaultInstance();
- User selectedUser = realm.where(User.class).equalTo("userID", currentUserID).findFirst();
- ArrayList<Integer> friendshipIds = new ArrayList<>();
- for (int i = 0; i < response.length(); i++) {
- try {
- final JSONObject jsonObject = response.getJSONObject(i);
- final int id = (int) (jsonObject.get("id"));
- if (id != ConfigurationManager.getInstance().getCurrentUserID()) {
- if (realm.where(User.class).equalTo("userID", id).findFirst() != null) {
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- try {
- User user = realm.where(User.class).equalTo("userID", id).findFirst();
- user.setCurrentUserID((int) jsonObject.get("current_user_id"));
- if (!jsonObject.isNull("profile_image")) {
- user.setProfileImage((String) jsonObject.get("profile_image"));
- }
- if (!jsonObject.isNull("email")) {
- user.setEmail((String) jsonObject.get("email"));
- }
- if (!jsonObject.isNull("name")) {
- user.setName((String) jsonObject.get("name"));
- }
- if (!jsonObject.isNull("telephone")) {
- user.setTelephone(jsonObject.getString("telephone"));
- }
- if (!jsonObject.isNull("date_of_birth")) {
- Date date = new SimpleDateFormat("yyyy-MM-dd").parse((String) jsonObject.get("date_of_birth"));
- user.setDateOfBirth(date);
- }
- realm.insertOrUpdate(user);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- } else {
- final User user = gson.fromJson(jsonObject.toString(), User.class);
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- realm.insertOrUpdate(user);
- }
- });
- }
- }
- final Friendship friendship = gson.fromJson(jsonObject.toString(), Friendship.class);
- friendshipIds.add(friendship.getFriendshipID());
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- realm.insertOrUpdate(friendship);
- }
- });
- RealmList<Friendship> list = selectedUser.getFriends();
- boolean containsFriend = false;
- for (Friendship friend : list) {
- if (friend.getFriendshipID()== friendship.getFriendshipID()) {
- containsFriend = true;
- }
- }
- if (!containsFriend) {
- if (realm.isInTransaction()) {
- selectedUser.addFriend(friendship);
- realm.insertOrUpdate(selectedUser);
- } else {
- realm.beginTransaction();
- selectedUser.addFriend(friendship);
- realm.insertOrUpdate(selectedUser);
- realm.commitTransaction();
- }
- }
- Log.w("Friends", selectedUser.getFriends().toString());
- } catch (Exception exception) {
- exception.printStackTrace();
- }
- }
- RealmResults<Friendship> friendships = realm.where(Friendship.class).equalTo("currentUserID", currentUserID).findAll();
- for (final Friendship friendship : friendships) {
- if (!friendshipIds.contains(friendship.getFriendshipID())) {
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- realm.insertOrUpdate(friendship);
- }
- });
- }
- }
- LocalBroadcastManager.getInstance(AppDelegate.getAppContext()).sendBroadcast(new Intent("friendsUpdated"));
- realm.close();
- if (callbackListener != null) {
- callbackListener.callback();
- }
- }
- }).start();
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- checkAuthorisation(error);
- }
- });
- VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(friendsRequest);
- }
- public void relationshipTypesRequest() {
- RelationshipTypesRequest relationshipTypesRequest = new RelationshipTypesRequest(new Response.Listener<JSONArray>() {
- @Override
- public void onResponse(JSONArray response) {
- for (int i = 0; i < response.length(); i++) {
- try {
- ;
- Realm realm = Realm.getDefaultInstance();
- final Gson gson = new Gson();
- final RelationshipType relationshipType = gson.fromJson(response.getJSONObject(i).toString(), RelationshipType.class);
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- realm.insertOrUpdate(relationshipType);
- }
- });
- realm.close();
- } catch (Exception exception) {
- exception.printStackTrace();
- }
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- checkAuthorisation(error);
- }
- });
- VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(relationshipTypesRequest);
- }
- public void getReceivedInvites(final CallbackListener callbackListener) {
- ReceivedInvites receivedInvites = new ReceivedInvites(new Response.Listener<JSONArray>() {
- @Override
- public void onResponse(JSONArray response) {
- for (int i = 0; i < response.length(); i++) {
- try {
- Realm realm = Realm.getDefaultInstance();
- final Gson gson = new Gson();
- final ReceivedInvite invite = gson.fromJson(response.getJSONObject(i).toString(), ReceivedInvite.class);
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- realm.insertOrUpdate(invite);
- }
- });
- realm.close();
- } catch (Exception exception) {
- exception.printStackTrace();
- }
- }
- if (callbackListener != null) {
- callbackListener.callback();
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- checkAuthorisation(error);
- }
- });
- VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(receivedInvites);
- }
- public void getSentInvites(final CallbackListener callbackListener) {
- SentInvites receivedInvites = new SentInvites(new Response.Listener<JSONArray>() {
- @Override
- public void onResponse(final JSONArray response) {
- Realm realm = Realm.getDefaultInstance();
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- realm.delete(SentInvite.class);
- }
- });
- realm.executeTransactionAsync(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- for (int i = 0; i < response.length(); i++) {
- try {
- final Gson gson = new Gson();
- SentInvite invite = gson.fromJson(response.getJSONObject(i).toString(), SentInvite.class);
- realm.insertOrUpdate(invite);
- } catch (Exception exception) {
- exception.printStackTrace();
- }
- }
- }
- }, new Realm.Transaction.OnSuccess() {
- @Override
- public void onSuccess() {
- if (callbackListener != null) {
- callbackListener.callback();
- }
- }
- });
- realm.close();
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- checkAuthorisation(error);
- }
- });
- VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(receivedInvites);
- }
- public void deleteSentInvite(final Context context, final int inviteID, final CallbackListener callbackListener) {
- DeleteSentInvite receivedInvites = new DeleteSentInvite(APIEndPoint.INVITES.urlString() + "/" + inviteID, new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- Realm realm = Realm.getDefaultInstance();
- final SentInvite sentInvite = realm.where(SentInvite.class).equalTo("inviteID", inviteID).findFirst();
- if (sentInvite != null) {
- final int sentInviteID = sentInvite.getInviteID();
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- SentInvite sentInvite = realm.where(SentInvite.class).equalTo("inviteID", sentInviteID).findFirst();
- if (sentInvite != null) {
- sentInvite.deleteFromRealm();
- }
- }
- });
- }
- realm.close();
- if (callbackListener != null) {
- callbackListener.callback();
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- volleyErrorHandler(error, context);
- }
- });
- VolleySingleton.getInstance(context).addToRequestQueue(receivedInvites);
- }
- public void updateFriendship(final Context context, int friendshipID, boolean canViewProfile, int relationshipID, final CallbackListener callbackListener) {
- Realm realm = Realm.getDefaultInstance();
- Friendship friendship = realm.where(Friendship.class).equalTo("friendshipID", friendshipID).findFirst();
- Map<String, Object> urlParams = new HashMap<String, Object>();
- urlParams.put("userID", friendship.getCurrentUserID());
- urlParams.put("friendID", friendship.getFriendshipID());
- String urlString = APIEndPoint.FRIENDS.urlString(urlParams);
- if (urlString == null) {
- Log.e("Error: ", "Cant construct url string");
- return;
- }
- Map<String, Object> paramsDict = new HashMap();
- paramsDict.put("can_view_profile", canViewProfile);
- paramsDict.put("relationship_type_id", relationshipID);
- Map<String, Object> params = new HashMap();
- params.put("relationship", paramsDict);
- JSONObject jsonObject = new JSONObject(params);
- VolleyPutRequest volleyPutRequest = new VolleyPutRequest(urlString, jsonObject, new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- try {
- Gson gson = new Gson();
- JSONObject jsonObject = new JSONObject(response.toString());
- final Friendship realmFriendship = gson.fromJson(jsonObject.toString(), Friendship.class);
- Realm realm = Realm.getDefaultInstance();
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- realm.insertOrUpdate(realmFriendship);
- }
- });
- realm.close();
- if (callbackListener != null) {
- callbackListener.callback();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- volleyErrorHandler(error, context);
- }
- });
- realm.close();
- VolleySingleton.getInstance(context).addToRequestQueue(volleyPutRequest);
- }
- public void deleteFriend(final Context context, final int friendshipID, final CallbackListener callbackListener) {
- Realm realm = Realm.getDefaultInstance();
- final Friendship friendship = realm.where(Friendship.class).equalTo("friendshipID", friendshipID).findFirst();
- Map<String, Object> urlParams = new HashMap<String, Object>();
- urlParams.put("userID", friendship.getCurrentUserID());
- urlParams.put("friendID", friendship.getFriendshipID());
- String urlString = APIEndPoint.FRIENDS.urlString(urlParams);
- if (urlString == null) {
- Log.e("Error: ", "Cant construct url string");
- return;
- }
- VolleyDeleteRequest deleteFriendRequest = new VolleyDeleteRequest(urlString, new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- Realm realm = Realm.getDefaultInstance();
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- final Friendship friendship = realm.where(Friendship.class).equalTo("friendshipID", friendshipID).findFirst();
- if (friendship != null) {
- friendship.deleteFromRealm();
- }
- }
- });
- callbackListener.callback();
- realm.close();
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- if (error.networkResponse.statusCode == 404) {
- Realm realm = Realm.getDefaultInstance();
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- final Friendship friendship = realm.where(Friendship.class).equalTo("friendshipID", friendshipID).findFirst();
- if (friendship != null) {
- friendship.deleteFromRealm();
- }
- }
- });
- callbackListener.callback();
- realm.close();
- } else {
- volleyErrorHandler(error, context);
- }
- }
- });
- VolleySingleton.getInstance(context).addToRequestQueue(deleteFriendRequest);
- realm.close();
- }
- public void declineFriendRequest(final Context context, final int inviteID, final CallbackListener callbackListener) {
- DeclineInvite declineInvite = new DeclineInvite(APIEndPoint.CONTRIBUTOR_INVITES.urlString() + "/" + inviteID, new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- callbackListener.callback();
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- volleyErrorHandler(error, context);
- }
- });
- VolleySingleton.getInstance(context).addToRequestQueue(declineInvite);
- }
- public void postLikeToMemory(final Context context, int userID, final int memoryID, final MemoriesViewHolder.LikeCallbackListener callbackListener) {
- Map<String, Object> urlParams = new HashMap<>();
- urlParams.put("userID", userID);
- urlParams.put("memoryID", memoryID);
- String urlString = APIEndPoint.MEMORY_EMOTIONS.urlString(urlParams);
- if (urlString == null) {
- Log.e("Error: ", "Cant construct url string");
- return;
- }
- VolleyPostArrayRequest likeMemoryRequest = new VolleyPostArrayRequest(urlString, null, new Response.Listener<JSONArray>() {
- @Override
- public void onResponse(final JSONArray response) {
- boolean userHasLiked = false;
- Realm realm = Realm.getDefaultInstance();
- for (int i = 0; i < response.length(); i++) {
- try {
- final MemoryEmotion memoryEmotion = new Gson().fromJson(response.getJSONObject(i).toString(), MemoryEmotion.class);
- if (memoryEmotion.getUserID() == ConfigurationManager.getInstance().getCurrentUserID()) {
- userHasLiked = true;
- }
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- realm.insertOrUpdate(memoryEmotion);
- }
- });
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- final boolean finalUserHasLiked = userHasLiked;
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- Memory memory = realm.where(Memory.class).equalTo("memoryID", memoryID).findFirst();
- if (memory != null) {
- if (finalUserHasLiked) {
- memory.setLovedByCurrentUser(true);
- } else {
- memory.setLovedByCurrentUser(false);
- }
- memory.setMemoryEmotionsCount(response.length());
- realm.insertOrUpdate(memory);
- }
- }
- });
- realm.close();
- callbackListener.callback(true);
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- Log.e("Volley Error", error + "");
- callbackListener.callback(false);
- }
- });
- VolleySingleton.getInstance(context).addToRequestQueue(likeMemoryRequest);
- }
- public void deleteLikeFromMemory(final Context context, int userID, final int memoryID, final MemoriesViewHolder.LikeCallbackListener callbackListener) {
- Map<String, Object> urlParams = new HashMap<>();
- urlParams.put("userID", userID);
- urlParams.put("memoryID", memoryID);
- String urlString = APIEndPoint.MEMORY_EMOTIONS.urlString(urlParams);
- if (urlString == null) {
- Log.e("Error: ", "Cant construct url string");
- return;
- }
- VolleyDeleteArrayRequest likeMemoryRequest = new VolleyDeleteArrayRequest(urlString + "/delete", new Response.Listener<JSONArray>() {
- @Override
- public void onResponse(final JSONArray response) {
- boolean userHasLiked = false;
- Realm realm = Realm.getDefaultInstance();
- for (int i = 0; i < response.length(); i++) {
- try {
- final MemoryEmotion memoryEmotion = new Gson().fromJson(response.getJSONObject(i).toString(), MemoryEmotion.class);
- if (memoryEmotion.getUserID() == ConfigurationManager.getInstance().getCurrentUserID()) {
- userHasLiked = true;
- }
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- realm.insertOrUpdate(memoryEmotion);
- }
- });
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- final boolean finalUserHasLiked = userHasLiked;
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- Memory memory = realm.where(Memory.class).equalTo("memoryID", memoryID).findFirst();
- if (memory != null) {
- if (finalUserHasLiked) {
- memory.setLovedByCurrentUser(true);
- } else {
- memory.setLovedByCurrentUser(false);
- }
- memory.setMemoryEmotionsCount(response.length());
- realm.insertOrUpdate(memory);
- }
- }
- });
- realm.close();
- callbackListener.callback(true);
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- Log.e("Volley Error", error + "");
- callbackListener.callback(false);
- }
- });
- VolleySingleton.getInstance(context).addToRequestQueue(likeMemoryRequest);
- }
- public void getNotifications(final Context context, final CallbackListener callbackListener) {
- final SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
- String lastDateTime = sharedPref.getString(context.getString(R.string.preference_latest_notification_time) + ConfigurationManager.getInstance().getCurrentUserID(), "");
- if (lastDateTime.equals("")) {
- Date date = Calendar.getInstance().getTime();
- SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
- lastDateTime = outputFmt.format(date);
- sharedPref.edit().putString(context.getString(R.string.preference_latest_notification_time) + ConfigurationManager.getInstance().getCurrentUserID(), lastDateTime).apply();
- }
- Map<String, Object> urlParams = new HashMap<>();
- urlParams.put("lastDateTime", lastDateTime);
- String urlString = APIEndPoint.NOTIFICATIONS.urlString(urlParams);
- VolleyGetArrayRequest getNotificationsRequest = new VolleyGetArrayRequest(urlString, new Response.Listener<JSONArray>() {
- @Override
- public void onResponse(JSONArray response) {
- for (int i = 0; i < response.length(); i++) {
- final int position = i;
- try {
- final Notification notification = new Gson().fromJson(response.getJSONObject(i).toString(), Notification.class);
- final Realm realm = Realm.getDefaultInstance();
- switch (notification.getNotificationType()) {
- case Notification.NEW_MEMORY:
- final Memory memory = realm.where(Memory.class).equalTo("memoryID", notification.getKeyID()).findFirst();
- if (memory == null) {
- Memory.getMemory(context, notification.getAboutUserID(), notification.getKeyID(), new CallbackListener() {
- @Override
- public void callback() {
- Realm realm = Realm.getDefaultInstance();
- Memory memory = realm.where(Memory.class).equalTo("memoryID", notification.getKeyID()).findFirst();
- notification.setMemory(memory);
- Notification.addToRealm(context, realm, notification, position, sharedPref, new CallbackListener() {
- @Override
- public void callback() {
- if (callbackListener != null) {
- callbackListener.callback();
- }
- }
- });
- realm.close();
- }
- });
- } else {
- notification.setMemory(memory);
- Notification.addToRealm(context, realm, notification, position, sharedPref, new CallbackListener() {
- @Override
- public void callback() {
- if (callbackListener != null) {
- callbackListener.callback();
- }
- }
- });
- }
- break;
- case Notification.MEMORY_EMOTION_COUNT_CHANGED:
- Memory.getMemory(context, notification.getAboutUserID(), notification.getKeyID(), new CallbackListener() {
- @Override
- public void callback() {
- Notification.addToRealm(context, realm, notification, position, sharedPref, new CallbackListener() {
- @Override
- public void callback() {
- if (callbackListener != null) {
- callbackListener.callback();
- }
- }
- });
- }
- });
- break;
- default:
- Notification.addToRealm(context, realm, notification, position, sharedPref, new CallbackListener() {
- @Override
- public void callback() {
- if (callbackListener != null) {
- callbackListener.callback();
- }
- }
- });
- break;
- }
- realm.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- Log.e("Volley Error", error +"");
- }
- });
- VolleySingleton.getInstance(context).addToRequestQueue(getNotificationsRequest);
- }
- public void postPurchaseToken(Context context, JSONArray purchases) {
- String urlString = APIEndPoint.VERIFY_ANDROID_RECEIPT.urlString();
- try {
- Map<String, JSONArray> params = new HashMap<>();
- params.put("purchases", purchases);
- VolleyPostRequest postPurchaseToken = new VolleyPostRequest(urlString, new JSONObject(params), new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- }
- });
- VolleySingleton.getInstance(context).addToRequestQueue(postPurchaseToken);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement