Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 44.33 KB | None | 0 0
  1. package com.myplaylifeapp.android.myplaylife.Configuration;
  2.  
  3. import android.app.AlertDialog;
  4. import android.content.Context;
  5. import android.content.DialogInterface;
  6. import android.content.Intent;
  7. import android.content.SharedPreferences;
  8. import android.support.v4.content.LocalBroadcastManager;
  9. import android.util.Log;
  10.  
  11. import com.android.volley.Response;
  12. import com.android.volley.error.VolleyError;
  13. import com.google.gson.Gson;
  14. import com.myplaylifeapp.android.myplaylife.CallbackListener;
  15. import com.myplaylifeapp.android.myplaylife.Interface.MainApp.UsersProfile.Memories.RecyclerView.MemoriesViewHolder;
  16. import com.myplaylifeapp.android.myplaylife.R;
  17. import com.myplaylifeapp.android.myplaylife.Realm.Objects.Friendship;
  18. import com.myplaylifeapp.android.myplaylife.Realm.Objects.Memory;
  19. import com.myplaylifeapp.android.myplaylife.Realm.Objects.MemoryEmotion;
  20. import com.myplaylifeapp.android.myplaylife.Realm.Objects.MemoryKeyword;
  21. import com.myplaylifeapp.android.myplaylife.Realm.Objects.MoodType;
  22. import com.myplaylifeapp.android.myplaylife.Realm.Objects.Notification;
  23. import com.myplaylifeapp.android.myplaylife.Realm.Objects.ReceivedInvite;
  24. import com.myplaylifeapp.android.myplaylife.Realm.Objects.RelationshipType;
  25. import com.myplaylifeapp.android.myplaylife.Realm.Objects.SentInvite;
  26. import com.myplaylifeapp.android.myplaylife.Realm.Objects.User;
  27. import com.myplaylifeapp.android.myplaylife.VolleyRequests.InvitesRequests.DeclineInvite;
  28. import com.myplaylifeapp.android.myplaylife.VolleyRequests.InvitesRequests.DeleteSentInvite;
  29. import com.myplaylifeapp.android.myplaylife.VolleyRequests.InvitesRequests.ReceivedInvites;
  30. import com.myplaylifeapp.android.myplaylife.VolleyRequests.InvitesRequests.SentInvites;
  31. import com.myplaylifeapp.android.myplaylife.VolleyRequests.KeywordsRequest;
  32. import com.myplaylifeapp.android.myplaylife.VolleyRequests.MoodsRequest;
  33. import com.myplaylifeapp.android.myplaylife.VolleyRequests.RelationshipTypesRequest;
  34. import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyDeleteArrayRequest;
  35. import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyDeleteRequest;
  36. import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyGetArrayRequest;
  37. import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyPostArrayRequest;
  38. import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyPostRequest;
  39. import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyPutRequest;
  40. import com.myplaylifeapp.android.myplaylife.VolleySingleton;
  41.  
  42. import org.json.JSONArray;
  43. import org.json.JSONException;
  44. import org.json.JSONObject;
  45.  
  46. import java.text.SimpleDateFormat;
  47. import java.util.ArrayList;
  48. import java.util.Calendar;
  49. import java.util.Date;
  50. import java.util.HashMap;
  51. import java.util.Map;
  52. import java.util.TimeZone;
  53.  
  54. import io.realm.Realm;
  55. import io.realm.RealmList;
  56. import io.realm.RealmResults;
  57.  
  58. /**
  59. * Created by jack on 20/02/2018.
  60. */
  61.  
  62. public class RequestOperations {
  63.  
  64. private static final RequestOperations sharedInstance = new RequestOperations();
  65.  
  66. public static RequestOperations getInstance() {
  67. return sharedInstance;
  68. }
  69.  
  70. public void volleyErrorHandler(VolleyError error, final Context context) {
  71. if (error != null && error.networkResponse != null && error.networkResponse.data != null) {
  72.  
  73. String errorString = "";
  74.  
  75. if (error.networkResponse.statusCode == 401) {
  76. try {
  77. AlertDialog alertDialog = new AlertDialog.Builder(context).create();
  78. alertDialog.setCancelable(false);
  79. alertDialog.setTitle("Unauthorised");
  80. alertDialog.setMessage("You have been logged out of the application");
  81. alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
  82. public void onClick(DialogInterface dialog, int which) {
  83. dialog.dismiss();
  84. ConfigurationManager.getInstance().logout(context);
  85. }
  86. });
  87.  
  88. alertDialog.show();
  89. } catch (Exception e) {
  90. ConfigurationManager.getInstance().logout(context);
  91. }
  92. }
  93.  
  94. try {
  95. JSONObject jobj = new JSONObject(new String(error.networkResponse.data));
  96. JSONArray errorArray = jobj.getJSONArray("errors");
  97.  
  98. for (int i = 0; i < errorArray.length(); i++) {
  99. Log.d("Volley Error", "" + errorArray.getString(i));
  100.  
  101. errorString = errorString + errorArray.getString(i) + "\n";
  102. }
  103. } catch (JSONException exception) {
  104. Log.d("Error", "" + "Error");
  105. }
  106.  
  107. try {
  108. AlertDialog alertDialog = new AlertDialog.Builder(context).create();
  109. alertDialog.setTitle("Error");
  110. alertDialog.setMessage(errorString);
  111. alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
  112. public void onClick(DialogInterface dialog, int which) {
  113. dialog.dismiss();
  114. }
  115. });
  116.  
  117. alertDialog.show();
  118. } catch (Exception e) {
  119. e.printStackTrace();
  120. }
  121.  
  122. } else {
  123.  
  124. try {
  125. AlertDialog alertDialog = new AlertDialog.Builder(context).create();
  126. alertDialog.setTitle("Error");
  127. alertDialog.setMessage("Cant connect to server");
  128. alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
  129. public void onClick(DialogInterface dialog, int which) {
  130. dialog.dismiss();
  131. }
  132. });
  133. alertDialog.show();
  134. } catch (Exception e) {
  135. e.printStackTrace();
  136. }
  137. }
  138. }
  139.  
  140. public void checkAuthorisation(VolleyError error) {
  141.  
  142. if (error != null && error.networkResponse != null && error.networkResponse.data != null) {
  143. if (error.networkResponse.statusCode == 401) {
  144. try {
  145.  
  146. Log.e("VolleyError", error.toString());
  147.  
  148. ConfigurationManager.getInstance().logout(AppDelegate.getAppContext());
  149.  
  150. } catch (Exception e) {
  151. e.printStackTrace();
  152. }
  153. }
  154. }
  155. }
  156.  
  157. public void forgotPasswordRequest(final String emailAddress, final Context context) {
  158.  
  159. String urlString = APIEndPoint.PASSWORD_RESETS.urlString();
  160.  
  161. Map<String, Object> params = new HashMap();
  162. params.put("email", emailAddress);
  163.  
  164. JSONObject jsonObject = new JSONObject(params);
  165.  
  166. VolleyPostRequest forgotPasswordRequest = new VolleyPostRequest(urlString, jsonObject, new Response.Listener<JSONObject>() {
  167. @Override
  168. public void onResponse(JSONObject response) {
  169. final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context)
  170. .setTitle("Success")
  171. .setMessage(String.format("An email has been sent to %s with password reset instructions", emailAddress))
  172. .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
  173. @Override
  174. public void onClick(DialogInterface dialog, int which) {
  175. dialog.dismiss();
  176. }
  177. });
  178. alertDialog.show();
  179. }
  180. }, new Response.ErrorListener() {
  181.  
  182. @Override
  183. public void onErrorResponse(VolleyError error) {
  184.  
  185. volleyErrorHandler(error, context);
  186. }
  187. });
  188. VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(forgotPasswordRequest);
  189. }
  190.  
  191. public void keywordsRequest() {
  192.  
  193. KeywordsRequest keywordsRequest = new KeywordsRequest(new Response.Listener<JSONArray>() {
  194. @Override
  195. public void onResponse(JSONArray response) {
  196.  
  197. Realm realm = Realm.getDefaultInstance();
  198.  
  199. final Gson gson = new Gson();
  200.  
  201. for (int i = 0; i < response.length(); i++) {
  202.  
  203. try {
  204. final JSONObject keywordObject = response.getJSONObject(i);
  205.  
  206. realm.executeTransaction(new Realm.Transaction() {
  207. @Override
  208. public void execute(Realm realm) {
  209. final MemoryKeyword memoryKeyword = gson.fromJson(keywordObject.toString(), MemoryKeyword.class);
  210. if (memoryKeyword != null) {
  211. realm.insertOrUpdate(memoryKeyword);
  212. }
  213. }
  214. });
  215.  
  216. } catch(JSONException exception) {
  217. Log.d("Keywords Response", "Failed to parse JSON object");
  218. }
  219. }
  220. realm.close();
  221.  
  222. }
  223. }, new Response.ErrorListener() {
  224.  
  225. @Override
  226. public void onErrorResponse(VolleyError error) {
  227.  
  228. checkAuthorisation(error);
  229. }
  230. });
  231. VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(keywordsRequest);
  232. }
  233.  
  234. public void moodsRequest() {
  235.  
  236. MoodsRequest moodsRequest = new MoodsRequest(new Response.Listener<JSONArray>() {
  237. @Override
  238. public void onResponse(JSONArray response) {
  239.  
  240. Realm realm = Realm.getDefaultInstance();
  241.  
  242. final Gson gson = new Gson();
  243.  
  244. for (int i = 0; i < response.length(); i++) {
  245.  
  246. try {
  247. final JSONObject moodObject = response.getJSONObject(i);
  248.  
  249. if (moodObject != null) {
  250.  
  251. realm.executeTransaction(new Realm.Transaction() {
  252. @Override
  253. public void execute(Realm realm) {
  254. final MoodType moodType = gson.fromJson(moodObject.toString(), MoodType.class);
  255.  
  256. if (moodType != null) {
  257. realm.insertOrUpdate(moodType);
  258. }
  259. }
  260. });
  261. }
  262.  
  263. } catch(JSONException exception) {
  264. Log.d("Moods Response", "Failed to parse JSON object");
  265. }
  266. }
  267. realm.close();
  268.  
  269. }
  270. }, new Response.ErrorListener() {
  271.  
  272. @Override
  273. public void onErrorResponse(VolleyError error) {
  274.  
  275. checkAuthorisation(error);
  276. }
  277. });
  278. VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(moodsRequest);
  279. }
  280.  
  281. public void friendsRequest(final int currentUserID, final int friendID, final CallbackListener callbackListener) {
  282.  
  283. final Map<String, Object> urlParams = new HashMap<String, Object>();
  284. urlParams.put("userID", currentUserID);
  285.  
  286. if (friendID != 0) {
  287. urlParams.put("friendID", friendID);
  288. }
  289.  
  290. final String urlString = APIEndPoint.FRIENDS.urlString(urlParams);
  291. if (urlString == null) {
  292. Log.e("Error: ", "Cant construct url string");
  293. return;
  294. }
  295.  
  296. VolleyGetArrayRequest friendsRequest = new VolleyGetArrayRequest(urlString, new Response.Listener<JSONArray>() {
  297. @Override
  298. public void onResponse(final JSONArray response) {
  299.  
  300. new Thread(new Runnable() {
  301. public void run() {
  302.  
  303. final Gson gson = new Gson();
  304.  
  305. Realm realm = Realm.getDefaultInstance();
  306.  
  307. User selectedUser = realm.where(User.class).equalTo("userID", currentUserID).findFirst();
  308.  
  309. ArrayList<Integer> friendshipIds = new ArrayList<>();
  310.  
  311. for (int i = 0; i < response.length(); i++) {
  312.  
  313. try {
  314.  
  315. final JSONObject jsonObject = response.getJSONObject(i);
  316. final int id = (int) (jsonObject.get("id"));
  317. if (id != ConfigurationManager.getInstance().getCurrentUserID()) {
  318.  
  319. if (realm.where(User.class).equalTo("userID", id).findFirst() != null) {
  320. realm.executeTransaction(new Realm.Transaction() {
  321. @Override
  322. public void execute(Realm realm) {
  323. try {
  324.  
  325. User user = realm.where(User.class).equalTo("userID", id).findFirst();
  326. user.setCurrentUserID((int) jsonObject.get("current_user_id"));
  327.  
  328. if (!jsonObject.isNull("profile_image")) {
  329.  
  330. user.setProfileImage((String) jsonObject.get("profile_image"));
  331. }
  332.  
  333. if (!jsonObject.isNull("email")) {
  334.  
  335. user.setEmail((String) jsonObject.get("email"));
  336. }
  337.  
  338. if (!jsonObject.isNull("name")) {
  339.  
  340. user.setName((String) jsonObject.get("name"));
  341. }
  342.  
  343. if (!jsonObject.isNull("telephone")) {
  344.  
  345. user.setTelephone(jsonObject.getString("telephone"));
  346. }
  347.  
  348. if (!jsonObject.isNull("date_of_birth")) {
  349.  
  350. Date date = new SimpleDateFormat("yyyy-MM-dd").parse((String) jsonObject.get("date_of_birth"));
  351. user.setDateOfBirth(date);
  352. }
  353.  
  354. realm.insertOrUpdate(user);
  355.  
  356. } catch (Exception e) {
  357. e.printStackTrace();
  358. }
  359. }
  360. });
  361. } else {
  362.  
  363. final User user = gson.fromJson(jsonObject.toString(), User.class);
  364. realm.executeTransaction(new Realm.Transaction() {
  365. @Override
  366. public void execute(Realm realm) {
  367. realm.insertOrUpdate(user);
  368. }
  369. });
  370. }
  371. }
  372.  
  373. final Friendship friendship = gson.fromJson(jsonObject.toString(), Friendship.class);
  374. friendshipIds.add(friendship.getFriendshipID());
  375. realm.executeTransaction(new Realm.Transaction() {
  376. @Override
  377. public void execute(Realm realm) {
  378. realm.insertOrUpdate(friendship);
  379. }
  380. });
  381.  
  382. RealmList<Friendship> list = selectedUser.getFriends();
  383.  
  384. boolean containsFriend = false;
  385. for (Friendship friend : list) {
  386.  
  387. if (friend.getFriendshipID()== friendship.getFriendshipID()) {
  388. containsFriend = true;
  389. }
  390. }
  391.  
  392. if (!containsFriend) {
  393.  
  394. if (realm.isInTransaction()) {
  395.  
  396. selectedUser.addFriend(friendship);
  397. realm.insertOrUpdate(selectedUser);
  398.  
  399. } else {
  400.  
  401. realm.beginTransaction();
  402. selectedUser.addFriend(friendship);
  403. realm.insertOrUpdate(selectedUser);
  404. realm.commitTransaction();
  405. }
  406. }
  407.  
  408. Log.w("Friends", selectedUser.getFriends().toString());
  409.  
  410. } catch (Exception exception) {
  411. exception.printStackTrace();
  412. }
  413. }
  414.  
  415. RealmResults<Friendship> friendships = realm.where(Friendship.class).equalTo("currentUserID", currentUserID).findAll();
  416. for (final Friendship friendship : friendships) {
  417. if (!friendshipIds.contains(friendship.getFriendshipID())) {
  418.  
  419. realm.executeTransaction(new Realm.Transaction() {
  420. @Override
  421. public void execute(Realm realm) {
  422. realm.insertOrUpdate(friendship);
  423. }
  424. });
  425. }
  426. }
  427.  
  428. LocalBroadcastManager.getInstance(AppDelegate.getAppContext()).sendBroadcast(new Intent("friendsUpdated"));
  429.  
  430. realm.close();
  431.  
  432. if (callbackListener != null) {
  433. callbackListener.callback();
  434. }
  435. }
  436. }).start();
  437. }
  438. }, new Response.ErrorListener() {
  439. @Override
  440. public void onErrorResponse(VolleyError error) {
  441.  
  442. checkAuthorisation(error);
  443. }
  444. });
  445. VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(friendsRequest);
  446. }
  447.  
  448. public void relationshipTypesRequest() {
  449.  
  450. RelationshipTypesRequest relationshipTypesRequest = new RelationshipTypesRequest(new Response.Listener<JSONArray>() {
  451. @Override
  452. public void onResponse(JSONArray response) {
  453.  
  454. for (int i = 0; i < response.length(); i++) {
  455. try {
  456. ;
  457. Realm realm = Realm.getDefaultInstance();
  458. final Gson gson = new Gson();
  459. final RelationshipType relationshipType = gson.fromJson(response.getJSONObject(i).toString(), RelationshipType.class);
  460. realm.executeTransaction(new Realm.Transaction() {
  461. @Override
  462. public void execute(Realm realm) {
  463. realm.insertOrUpdate(relationshipType);
  464. }
  465. });
  466. realm.close();
  467. } catch (Exception exception) {
  468. exception.printStackTrace();
  469. }
  470. }
  471. }
  472. }, new Response.ErrorListener() {
  473. @Override
  474. public void onErrorResponse(VolleyError error) {
  475.  
  476. checkAuthorisation(error);
  477. }
  478. });
  479. VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(relationshipTypesRequest);
  480. }
  481.  
  482. public void getReceivedInvites(final CallbackListener callbackListener) {
  483.  
  484. ReceivedInvites receivedInvites = new ReceivedInvites(new Response.Listener<JSONArray>() {
  485. @Override
  486. public void onResponse(JSONArray response) {
  487.  
  488. for (int i = 0; i < response.length(); i++) {
  489. try {
  490.  
  491. Realm realm = Realm.getDefaultInstance();
  492. final Gson gson = new Gson();
  493. final ReceivedInvite invite = gson.fromJson(response.getJSONObject(i).toString(), ReceivedInvite.class);
  494. realm.executeTransaction(new Realm.Transaction() {
  495. @Override
  496. public void execute(Realm realm) {
  497. realm.insertOrUpdate(invite);
  498. }
  499. });
  500. realm.close();
  501. } catch (Exception exception) {
  502. exception.printStackTrace();
  503. }
  504. }
  505.  
  506. if (callbackListener != null) {
  507. callbackListener.callback();
  508. }
  509. }
  510. }, new Response.ErrorListener() {
  511. @Override
  512. public void onErrorResponse(VolleyError error) {
  513.  
  514. checkAuthorisation(error);
  515. }
  516. });
  517. VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(receivedInvites);
  518. }
  519.  
  520. public void getSentInvites(final CallbackListener callbackListener) {
  521.  
  522. SentInvites receivedInvites = new SentInvites(new Response.Listener<JSONArray>() {
  523. @Override
  524. public void onResponse(final JSONArray response) {
  525.  
  526. Realm realm = Realm.getDefaultInstance();
  527.  
  528. realm.executeTransaction(new Realm.Transaction() {
  529. @Override
  530. public void execute(Realm realm) {
  531. realm.delete(SentInvite.class);
  532. }
  533. });
  534.  
  535. realm.executeTransactionAsync(new Realm.Transaction() {
  536. @Override
  537. public void execute(Realm realm) {
  538. for (int i = 0; i < response.length(); i++) {
  539. try {
  540. final Gson gson = new Gson();
  541. SentInvite invite = gson.fromJson(response.getJSONObject(i).toString(), SentInvite.class);
  542. realm.insertOrUpdate(invite);
  543. } catch (Exception exception) {
  544. exception.printStackTrace();
  545. }
  546. }
  547. }
  548. }, new Realm.Transaction.OnSuccess() {
  549. @Override
  550. public void onSuccess() {
  551. if (callbackListener != null) {
  552. callbackListener.callback();
  553. }
  554. }
  555. });
  556.  
  557. realm.close();
  558. }
  559. }, new Response.ErrorListener() {
  560. @Override
  561. public void onErrorResponse(VolleyError error) {
  562.  
  563. checkAuthorisation(error);
  564. }
  565. });
  566. VolleySingleton.getInstance(AppDelegate.getAppContext().getApplicationContext()).addToRequestQueue(receivedInvites);
  567. }
  568.  
  569. public void deleteSentInvite(final Context context, final int inviteID, final CallbackListener callbackListener) {
  570.  
  571. DeleteSentInvite receivedInvites = new DeleteSentInvite(APIEndPoint.INVITES.urlString() + "/" + inviteID, new Response.Listener<JSONObject>() {
  572. @Override
  573. public void onResponse(JSONObject response) {
  574.  
  575. Realm realm = Realm.getDefaultInstance();
  576.  
  577. final SentInvite sentInvite = realm.where(SentInvite.class).equalTo("inviteID", inviteID).findFirst();
  578.  
  579. if (sentInvite != null) {
  580.  
  581. final int sentInviteID = sentInvite.getInviteID();
  582.  
  583. realm.executeTransaction(new Realm.Transaction() {
  584. @Override
  585. public void execute(Realm realm) {
  586. SentInvite sentInvite = realm.where(SentInvite.class).equalTo("inviteID", sentInviteID).findFirst();
  587. if (sentInvite != null) {
  588. sentInvite.deleteFromRealm();
  589. }
  590. }
  591. });
  592. }
  593. realm.close();
  594.  
  595. if (callbackListener != null) {
  596. callbackListener.callback();
  597. }
  598. }
  599. }, new Response.ErrorListener() {
  600. @Override
  601. public void onErrorResponse(VolleyError error) {
  602.  
  603. volleyErrorHandler(error, context);
  604. }
  605. });
  606. VolleySingleton.getInstance(context).addToRequestQueue(receivedInvites);
  607. }
  608.  
  609. public void updateFriendship(final Context context, int friendshipID, boolean canViewProfile, int relationshipID, final CallbackListener callbackListener) {
  610.  
  611. Realm realm = Realm.getDefaultInstance();
  612. Friendship friendship = realm.where(Friendship.class).equalTo("friendshipID", friendshipID).findFirst();
  613.  
  614. Map<String, Object> urlParams = new HashMap<String, Object>();
  615. urlParams.put("userID", friendship.getCurrentUserID());
  616. urlParams.put("friendID", friendship.getFriendshipID());
  617.  
  618. String urlString = APIEndPoint.FRIENDS.urlString(urlParams);
  619. if (urlString == null) {
  620. Log.e("Error: ", "Cant construct url string");
  621. return;
  622. }
  623.  
  624. Map<String, Object> paramsDict = new HashMap();
  625. paramsDict.put("can_view_profile", canViewProfile);
  626. paramsDict.put("relationship_type_id", relationshipID);
  627.  
  628. Map<String, Object> params = new HashMap();
  629. params.put("relationship", paramsDict);
  630.  
  631. JSONObject jsonObject = new JSONObject(params);
  632.  
  633. VolleyPutRequest volleyPutRequest = new VolleyPutRequest(urlString, jsonObject, new Response.Listener<JSONObject>() {
  634. @Override
  635. public void onResponse(JSONObject response) {
  636.  
  637. try {
  638. Gson gson = new Gson();
  639. JSONObject jsonObject = new JSONObject(response.toString());
  640.  
  641.  
  642. final Friendship realmFriendship = gson.fromJson(jsonObject.toString(), Friendship.class);
  643. Realm realm = Realm.getDefaultInstance();
  644. realm.executeTransaction(new Realm.Transaction() {
  645. @Override
  646. public void execute(Realm realm) {
  647. realm.insertOrUpdate(realmFriendship);
  648. }
  649. });
  650. realm.close();
  651.  
  652. if (callbackListener != null) {
  653. callbackListener.callback();
  654. }
  655.  
  656. } catch (Exception e) {
  657. e.printStackTrace();
  658. }
  659. }
  660. }, new Response.ErrorListener() {
  661. @Override
  662. public void onErrorResponse(VolleyError error) {
  663. volleyErrorHandler(error, context);
  664. }
  665. });
  666.  
  667. realm.close();
  668.  
  669. VolleySingleton.getInstance(context).addToRequestQueue(volleyPutRequest);
  670. }
  671.  
  672. public void deleteFriend(final Context context, final int friendshipID, final CallbackListener callbackListener) {
  673.  
  674. Realm realm = Realm.getDefaultInstance();
  675.  
  676. final Friendship friendship = realm.where(Friendship.class).equalTo("friendshipID", friendshipID).findFirst();
  677.  
  678. Map<String, Object> urlParams = new HashMap<String, Object>();
  679. urlParams.put("userID", friendship.getCurrentUserID());
  680. urlParams.put("friendID", friendship.getFriendshipID());
  681.  
  682. String urlString = APIEndPoint.FRIENDS.urlString(urlParams);
  683. if (urlString == null) {
  684. Log.e("Error: ", "Cant construct url string");
  685. return;
  686. }
  687.  
  688. VolleyDeleteRequest deleteFriendRequest = new VolleyDeleteRequest(urlString, new Response.Listener<JSONObject>() {
  689. @Override
  690. public void onResponse(JSONObject response) {
  691. Realm realm = Realm.getDefaultInstance();
  692.  
  693. realm.executeTransaction(new Realm.Transaction() {
  694. @Override
  695. public void execute(Realm realm) {
  696. final Friendship friendship = realm.where(Friendship.class).equalTo("friendshipID", friendshipID).findFirst();
  697. if (friendship != null) {
  698. friendship.deleteFromRealm();
  699. }
  700. }
  701. });
  702.  
  703. callbackListener.callback();
  704.  
  705. realm.close();
  706. }
  707. }, new Response.ErrorListener() {
  708. @Override
  709. public void onErrorResponse(VolleyError error) {
  710.  
  711. if (error.networkResponse.statusCode == 404) {
  712. Realm realm = Realm.getDefaultInstance();
  713.  
  714. realm.executeTransaction(new Realm.Transaction() {
  715. @Override
  716. public void execute(Realm realm) {
  717. final Friendship friendship = realm.where(Friendship.class).equalTo("friendshipID", friendshipID).findFirst();
  718. if (friendship != null) {
  719. friendship.deleteFromRealm();
  720. }
  721. }
  722. });
  723.  
  724. callbackListener.callback();
  725.  
  726. realm.close();
  727. } else {
  728. volleyErrorHandler(error, context);
  729. }
  730. }
  731. });
  732. VolleySingleton.getInstance(context).addToRequestQueue(deleteFriendRequest);
  733.  
  734. realm.close();
  735. }
  736.  
  737. public void declineFriendRequest(final Context context, final int inviteID, final CallbackListener callbackListener) {
  738.  
  739. DeclineInvite declineInvite = new DeclineInvite(APIEndPoint.CONTRIBUTOR_INVITES.urlString() + "/" + inviteID, new Response.Listener<JSONObject>() {
  740. @Override
  741. public void onResponse(JSONObject response) {
  742.  
  743. callbackListener.callback();
  744. }
  745. }, new Response.ErrorListener() {
  746. @Override
  747. public void onErrorResponse(VolleyError error) {
  748.  
  749. volleyErrorHandler(error, context);
  750. }
  751. });
  752. VolleySingleton.getInstance(context).addToRequestQueue(declineInvite);
  753. }
  754.  
  755. public void postLikeToMemory(final Context context, int userID, final int memoryID, final MemoriesViewHolder.LikeCallbackListener callbackListener) {
  756.  
  757. Map<String, Object> urlParams = new HashMap<>();
  758. urlParams.put("userID", userID);
  759. urlParams.put("memoryID", memoryID);
  760.  
  761. String urlString = APIEndPoint.MEMORY_EMOTIONS.urlString(urlParams);
  762. if (urlString == null) {
  763. Log.e("Error: ", "Cant construct url string");
  764. return;
  765. }
  766.  
  767. VolleyPostArrayRequest likeMemoryRequest = new VolleyPostArrayRequest(urlString, null, new Response.Listener<JSONArray>() {
  768. @Override
  769. public void onResponse(final JSONArray response) {
  770.  
  771. boolean userHasLiked = false;
  772.  
  773. Realm realm = Realm.getDefaultInstance();
  774.  
  775. for (int i = 0; i < response.length(); i++) {
  776. try {
  777. final MemoryEmotion memoryEmotion = new Gson().fromJson(response.getJSONObject(i).toString(), MemoryEmotion.class);
  778.  
  779. if (memoryEmotion.getUserID() == ConfigurationManager.getInstance().getCurrentUserID()) {
  780. userHasLiked = true;
  781. }
  782.  
  783. realm.executeTransaction(new Realm.Transaction() {
  784. @Override
  785. public void execute(Realm realm) {
  786. realm.insertOrUpdate(memoryEmotion);
  787. }
  788. });
  789. } catch (Exception e) {
  790. e.printStackTrace();
  791. }
  792. }
  793.  
  794. final boolean finalUserHasLiked = userHasLiked;
  795. realm.executeTransaction(new Realm.Transaction() {
  796. @Override
  797. public void execute(Realm realm) {
  798. Memory memory = realm.where(Memory.class).equalTo("memoryID", memoryID).findFirst();
  799. if (memory != null) {
  800. if (finalUserHasLiked) {
  801. memory.setLovedByCurrentUser(true);
  802. } else {
  803. memory.setLovedByCurrentUser(false);
  804. }
  805. memory.setMemoryEmotionsCount(response.length());
  806.  
  807. realm.insertOrUpdate(memory);
  808. }
  809. }
  810. });
  811.  
  812. realm.close();
  813.  
  814. callbackListener.callback(true);
  815. }
  816. }, new Response.ErrorListener() {
  817. @Override
  818. public void onErrorResponse(VolleyError error) {
  819. Log.e("Volley Error", error + "");
  820.  
  821. callbackListener.callback(false);
  822. }
  823. });
  824. VolleySingleton.getInstance(context).addToRequestQueue(likeMemoryRequest);
  825. }
  826.  
  827. public void deleteLikeFromMemory(final Context context, int userID, final int memoryID, final MemoriesViewHolder.LikeCallbackListener callbackListener) {
  828.  
  829. Map<String, Object> urlParams = new HashMap<>();
  830. urlParams.put("userID", userID);
  831. urlParams.put("memoryID", memoryID);
  832.  
  833. String urlString = APIEndPoint.MEMORY_EMOTIONS.urlString(urlParams);
  834. if (urlString == null) {
  835. Log.e("Error: ", "Cant construct url string");
  836. return;
  837. }
  838.  
  839. VolleyDeleteArrayRequest likeMemoryRequest = new VolleyDeleteArrayRequest(urlString + "/delete", new Response.Listener<JSONArray>() {
  840. @Override
  841. public void onResponse(final JSONArray response) {
  842.  
  843. boolean userHasLiked = false;
  844.  
  845. Realm realm = Realm.getDefaultInstance();
  846.  
  847. for (int i = 0; i < response.length(); i++) {
  848. try {
  849. final MemoryEmotion memoryEmotion = new Gson().fromJson(response.getJSONObject(i).toString(), MemoryEmotion.class);
  850.  
  851. if (memoryEmotion.getUserID() == ConfigurationManager.getInstance().getCurrentUserID()) {
  852. userHasLiked = true;
  853. }
  854.  
  855. realm.executeTransaction(new Realm.Transaction() {
  856. @Override
  857. public void execute(Realm realm) {
  858. realm.insertOrUpdate(memoryEmotion);
  859. }
  860. });
  861. } catch (Exception e) {
  862. e.printStackTrace();
  863. }
  864. }
  865.  
  866. final boolean finalUserHasLiked = userHasLiked;
  867. realm.executeTransaction(new Realm.Transaction() {
  868. @Override
  869. public void execute(Realm realm) {
  870. Memory memory = realm.where(Memory.class).equalTo("memoryID", memoryID).findFirst();
  871. if (memory != null) {
  872. if (finalUserHasLiked) {
  873. memory.setLovedByCurrentUser(true);
  874. } else {
  875. memory.setLovedByCurrentUser(false);
  876. }
  877. memory.setMemoryEmotionsCount(response.length());
  878.  
  879. realm.insertOrUpdate(memory);
  880. }
  881. }
  882. });
  883. realm.close();
  884.  
  885. callbackListener.callback(true);
  886. }
  887. }, new Response.ErrorListener() {
  888. @Override
  889. public void onErrorResponse(VolleyError error) {
  890. Log.e("Volley Error", error + "");
  891.  
  892. callbackListener.callback(false);
  893. }
  894. });
  895. VolleySingleton.getInstance(context).addToRequestQueue(likeMemoryRequest);
  896. }
  897.  
  898. public void getNotifications(final Context context, final CallbackListener callbackListener) {
  899.  
  900. final SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
  901.  
  902. String lastDateTime = sharedPref.getString(context.getString(R.string.preference_latest_notification_time) + ConfigurationManager.getInstance().getCurrentUserID(), "");
  903.  
  904. if (lastDateTime.equals("")) {
  905. Date date = Calendar.getInstance().getTime();
  906.  
  907. SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  908. outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
  909. lastDateTime = outputFmt.format(date);
  910.  
  911. sharedPref.edit().putString(context.getString(R.string.preference_latest_notification_time) + ConfigurationManager.getInstance().getCurrentUserID(), lastDateTime).apply();
  912. }
  913.  
  914. Map<String, Object> urlParams = new HashMap<>();
  915. urlParams.put("lastDateTime", lastDateTime);
  916.  
  917. String urlString = APIEndPoint.NOTIFICATIONS.urlString(urlParams);
  918.  
  919. VolleyGetArrayRequest getNotificationsRequest = new VolleyGetArrayRequest(urlString, new Response.Listener<JSONArray>() {
  920. @Override
  921. public void onResponse(JSONArray response) {
  922.  
  923. for (int i = 0; i < response.length(); i++) {
  924.  
  925. final int position = i;
  926.  
  927. try {
  928. final Notification notification = new Gson().fromJson(response.getJSONObject(i).toString(), Notification.class);
  929.  
  930. final Realm realm = Realm.getDefaultInstance();
  931.  
  932. switch (notification.getNotificationType()) {
  933. case Notification.NEW_MEMORY:
  934. final Memory memory = realm.where(Memory.class).equalTo("memoryID", notification.getKeyID()).findFirst();
  935.  
  936. if (memory == null) {
  937. Memory.getMemory(context, notification.getAboutUserID(), notification.getKeyID(), new CallbackListener() {
  938. @Override
  939. public void callback() {
  940. Realm realm = Realm.getDefaultInstance();
  941. Memory memory = realm.where(Memory.class).equalTo("memoryID", notification.getKeyID()).findFirst();
  942. notification.setMemory(memory);
  943. Notification.addToRealm(context, realm, notification, position, sharedPref, new CallbackListener() {
  944. @Override
  945. public void callback() {
  946. if (callbackListener != null) {
  947. callbackListener.callback();
  948. }
  949. }
  950. });
  951. realm.close();
  952. }
  953. });
  954. } else {
  955. notification.setMemory(memory);
  956. Notification.addToRealm(context, realm, notification, position, sharedPref, new CallbackListener() {
  957. @Override
  958. public void callback() {
  959. if (callbackListener != null) {
  960. callbackListener.callback();
  961. }
  962. }
  963. });
  964. }
  965. break;
  966.  
  967. case Notification.MEMORY_EMOTION_COUNT_CHANGED:
  968. Memory.getMemory(context, notification.getAboutUserID(), notification.getKeyID(), new CallbackListener() {
  969. @Override
  970. public void callback() {
  971. Notification.addToRealm(context, realm, notification, position, sharedPref, new CallbackListener() {
  972. @Override
  973. public void callback() {
  974. if (callbackListener != null) {
  975. callbackListener.callback();
  976. }
  977. }
  978. });
  979. }
  980. });
  981. break;
  982.  
  983. default:
  984. Notification.addToRealm(context, realm, notification, position, sharedPref, new CallbackListener() {
  985. @Override
  986. public void callback() {
  987. if (callbackListener != null) {
  988. callbackListener.callback();
  989. }
  990. }
  991. });
  992. break;
  993. }
  994. realm.close();
  995.  
  996. } catch (Exception e) {
  997. e.printStackTrace();
  998. }
  999. }
  1000. }
  1001. }, new Response.ErrorListener() {
  1002. @Override
  1003. public void onErrorResponse(VolleyError error) {
  1004. Log.e("Volley Error", error +"");
  1005. }
  1006. });
  1007. VolleySingleton.getInstance(context).addToRequestQueue(getNotificationsRequest);
  1008. }
  1009.  
  1010. public void postPurchaseToken(Context context, JSONArray purchases) {
  1011.  
  1012. String urlString = APIEndPoint.VERIFY_ANDROID_RECEIPT.urlString();
  1013.  
  1014.  
  1015. try {
  1016.  
  1017. Map<String, JSONArray> params = new HashMap<>();
  1018. params.put("purchases", purchases);
  1019.  
  1020. VolleyPostRequest postPurchaseToken = new VolleyPostRequest(urlString, new JSONObject(params), new Response.Listener<JSONObject>() {
  1021. @Override
  1022. public void onResponse(JSONObject response) {
  1023.  
  1024. }
  1025. }, new Response.ErrorListener() {
  1026. @Override
  1027. public void onErrorResponse(VolleyError error) {
  1028.  
  1029. }
  1030. });
  1031. VolleySingleton.getInstance(context).addToRequestQueue(postPurchaseToken);
  1032. } catch (Exception e) {
  1033. e.printStackTrace();
  1034. }
  1035. }
  1036. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement