Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.61 KB | None | 0 0
  1. package com.myplaylifeapp.android.myplaylife.Realm.Objects;
  2.  
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.SharedPreferences;
  6. import android.os.Build;
  7. import android.support.annotation.NonNull;
  8. import android.support.v4.content.LocalBroadcastManager;
  9. import android.util.Log;
  10.  
  11. import com.android.volley.Request;
  12. import com.android.volley.Response;
  13. import com.android.volley.error.VolleyError;
  14. import com.google.android.gms.tasks.OnCompleteListener;
  15. import com.google.android.gms.tasks.Task;
  16. import com.google.firebase.iid.FirebaseInstanceId;
  17. import com.google.firebase.iid.InstanceIdResult;
  18. import com.google.gson.Gson;
  19. import com.google.gson.annotations.SerializedName;
  20. import com.myplaylifeapp.android.myplaylife.BuildConfig;
  21. import com.myplaylifeapp.android.myplaylife.Configuration.APIEndPoint;
  22. import com.myplaylifeapp.android.myplaylife.Configuration.AppDelegate;
  23. import com.myplaylifeapp.android.myplaylife.Configuration.ConfigurationManager;
  24. import com.myplaylifeapp.android.myplaylife.Configuration.DeviceInfo;
  25. import com.myplaylifeapp.android.myplaylife.Configuration.RequestOperations;
  26. import com.myplaylifeapp.android.myplaylife.Notifications.MyPlayLifeFirebaseMessagingService;
  27. import com.myplaylifeapp.android.myplaylife.R;
  28. import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyDefaultRequest;
  29. import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyGetRequest;
  30. import com.myplaylifeapp.android.myplaylife.VolleySingleton;
  31.  
  32. import org.json.JSONObject;
  33.  
  34. import java.util.Date;
  35. import java.util.HashMap;
  36. import java.util.Map;
  37. import java.util.UUID;
  38.  
  39. import io.realm.Realm;
  40. import io.realm.RealmList;
  41. import io.realm.RealmObject;
  42. import io.realm.annotations.PrimaryKey;
  43.  
  44. /**
  45. * Created by jack on 05/02/2018.
  46. */
  47.  
  48. public class User extends RealmObject {
  49.  
  50. @PrimaryKey
  51. @SerializedName("id")
  52. private int userID;
  53.  
  54. @SerializedName("current_user_id")
  55. private int currentUserID;
  56.  
  57. @SerializedName("email")
  58. private String email;
  59.  
  60. @SerializedName("name")
  61. private String name;
  62.  
  63. @SerializedName("access_token")
  64. private String accessToken;
  65.  
  66. @SerializedName("date_of_birth")
  67. private Date dateOfBirth;
  68.  
  69. @SerializedName("telephone")
  70. private String telephone;
  71.  
  72. @SerializedName("profile_image")
  73. private String profileImage;
  74.  
  75. private String currentDeviceID;
  76.  
  77. private String profileImageSignature = UUID.randomUUID().toString();
  78.  
  79. private String fullProfileImageSignature = UUID.randomUUID().toString();
  80.  
  81. // private String devicePushToken;
  82.  
  83. private RealmList<Friendship> friends = new RealmList<>();
  84.  
  85. public static void updateUser(Context context) {
  86.  
  87. final Map<String, Object> urlParams = new HashMap<>();
  88. urlParams.put("userID", ConfigurationManager.getInstance().getCurrentUserID());
  89.  
  90. String urlString = APIEndPoint.USERS.urlString(urlParams);
  91.  
  92. final VolleyGetRequest userRequest = new VolleyGetRequest(urlString, new Response.Listener<JSONObject>() {
  93. @Override
  94. public void onResponse(final JSONObject response) {
  95.  
  96. try {
  97. Realm realm = Realm.getDefaultInstance();
  98. final JSONObject jsonObject = new JSONObject(response.toString());
  99.  
  100. final User gsonUser = new Gson().fromJson(jsonObject.toString(), User.class);
  101.  
  102. User user = realm.where(User.class).equalTo("userID", gsonUser.getUserID()).findFirst();
  103.  
  104. if (user != null) {
  105.  
  106. realm.executeTransaction(new Realm.Transaction() {
  107. @Override
  108. public void execute(Realm realm) {
  109.  
  110. try {
  111.  
  112. User user = realm.where(User.class).equalTo("userID", gsonUser.getUserID()).findFirst();
  113.  
  114. user.setCurrentUserID(gsonUser.currentUserID);
  115.  
  116. user.setProfileImage(gsonUser.getProfileImage());
  117.  
  118. user.setEmail(gsonUser.getEmail());
  119.  
  120. user.setName(gsonUser.getName());
  121.  
  122. user.setTelephone(gsonUser.getTelephone());
  123.  
  124. user.setDateOfBirth(gsonUser.getDateOfBirth());
  125.  
  126. realm.insertOrUpdate(user);
  127.  
  128. LocalBroadcastManager.getInstance(AppDelegate.getAppContext()).sendBroadcast(new Intent("profilePictureUpdated"));
  129.  
  130. } catch (Exception e) {
  131. e.printStackTrace();
  132. }
  133. }
  134. });
  135.  
  136. } else {
  137. realm.executeTransaction(new Realm.Transaction() {
  138. @Override
  139. public void execute(Realm realm) {
  140. realm.insertOrUpdate(gsonUser);
  141. }
  142. });
  143. }
  144.  
  145. realm.close();
  146. } catch (Exception e) {
  147. e.printStackTrace();
  148. }
  149.  
  150. }
  151. }, new Response.ErrorListener() {
  152. @Override
  153. public void onErrorResponse(VolleyError error) {
  154. Log.e("GlideImageLoader", "Failed to download user object");
  155. RequestOperations.getInstance().checkAuthorisation(error);
  156. }
  157. });
  158. VolleySingleton.getInstance(context).addToRequestQueue(userRequest);
  159. }
  160.  
  161. public void uploadDeviceInfo(final Context context, final MyPlayLifeFirebaseMessagingService.TokenUpdatedCallback tokenUpdatedCallback) {
  162.  
  163. FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
  164.  
  165. int realmUserID = userID;
  166.  
  167. @Override
  168. public void onComplete(@NonNull Task<InstanceIdResult> task) {
  169. if (!task.isSuccessful()) {
  170. Log.w("FirebaseID", "getInstanceId failed", task.getException());
  171. return;
  172. }
  173.  
  174. // realm closed at this point, recreated on new thread to post the device information
  175.  
  176. Realm realm = Realm.getDefaultInstance();
  177.  
  178. User user = realm.where(User.class).equalTo("userID", realmUserID).findFirst();
  179. if (user != null) {
  180. user.postOrPutDeviceInfo(context, task.getResult().getToken(), tokenUpdatedCallback);
  181. }
  182.  
  183. realm.close();
  184. }
  185. });
  186. }
  187.  
  188. public void postOrPutDeviceInfo(final Context context, final String deviceToken, final MyPlayLifeFirebaseMessagingService.TokenUpdatedCallback tokenUpdatedCallback) {
  189.  
  190. SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
  191.  
  192. final int deviceID = sharedPref.getInt(context.getString(R.string.userDeviceIDForUserID_) + userID, 0);
  193.  
  194. int postOrPatch;
  195. String urlString;
  196.  
  197. if (deviceID == 0) {
  198. postOrPatch = Request.Method.POST;
  199. urlString = APIEndPoint.USER_DEVICES.urlString();
  200.  
  201. } else {
  202. postOrPatch = Request.Method.PATCH;
  203. urlString = APIEndPoint.USER_DEVICES.urlString() + "/" + deviceID;
  204. }
  205.  
  206. Map<String, String> paramsDict = new HashMap<>();
  207. paramsDict.put("token", deviceToken);
  208. paramsDict.put("app_version", BuildConfig.VERSION_NAME);
  209. paramsDict.put("system_name", "Android");
  210. paramsDict.put("system_version", Build.VERSION.RELEASE);
  211. paramsDict.put("device_model", DeviceInfo.getDeviceName());
  212.  
  213. JSONObject params = new JSONObject(paramsDict);
  214.  
  215. final int realmUserID = userID;
  216.  
  217. VolleyDefaultRequest uploadDeviceInfo = new VolleyDefaultRequest(postOrPatch, urlString, params, new Response.Listener<JSONObject>() {
  218. @Override
  219. public void onResponse(JSONObject response) {
  220.  
  221. if (realmUserID != 0) {
  222.  
  223. try {
  224. int deviceID = response.getInt("id");
  225.  
  226. SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
  227.  
  228. sharedPref.edit().putInt(context.getString(R.string.userDeviceIDForUserID_) + realmUserID, deviceID).apply();
  229.  
  230. } catch (Exception exception) {
  231. Log.d("Exception", "Could Not Save To Shared Preferences");
  232. }
  233. }
  234.  
  235. if (tokenUpdatedCallback != null) {
  236. tokenUpdatedCallback.callback(true);
  237. }
  238. }
  239. }, new Response.ErrorListener() {
  240. @Override
  241. public void onErrorResponse(VolleyError error) {
  242. RequestOperations.getInstance().volleyErrorHandler(error, context);
  243. Log.d("Error:", "Failed to connect to server - sending pushToken");
  244.  
  245. if (tokenUpdatedCallback != null) {
  246. tokenUpdatedCallback.callback(false);
  247. }
  248. }
  249. });
  250. VolleySingleton.getInstance(context).addToRequestQueue(uploadDeviceInfo);
  251. }
  252.  
  253. public void deleteUserDeviceID(final Context context) {
  254.  
  255. SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
  256.  
  257. int deviceID = sharedPref.getInt(context.getString(R.string.userDeviceIDForUserID_) + userID, 0);
  258.  
  259. String urlString = APIEndPoint.USER_DEVICES.urlString() + "/" + deviceID;
  260.  
  261. VolleyDefaultRequest deleteDeviceInfo = new VolleyDefaultRequest(Request.Method.DELETE, urlString, null, new Response.Listener<JSONObject>() {
  262. @Override
  263. public void onResponse(JSONObject response) {
  264.  
  265. }
  266. }, new Response.ErrorListener() {
  267. @Override
  268. public void onErrorResponse(VolleyError error) {
  269. }
  270. });
  271. VolleySingleton.getInstance(context).addToRequestQueue(deleteDeviceInfo);
  272. }
  273.  
  274. public int getUserID() {
  275. return userID;
  276. }
  277.  
  278. public void setUserID(int userID) {
  279. this.userID = userID;
  280. }
  281.  
  282. public int getCurrentUserID() {
  283. return currentUserID;
  284. }
  285.  
  286. public void setCurrentUserID(int currentUserID) {
  287. this.currentUserID = currentUserID;
  288. }
  289.  
  290. public String getEmail() {
  291. return email;
  292. }
  293.  
  294. public void setEmail(String email) {
  295. this.email = email;
  296. }
  297.  
  298. public String getName() {
  299. return name;
  300. }
  301.  
  302. public void setName(String name) {
  303. this.name = name;
  304. }
  305.  
  306. public String getAccessToken() {
  307. return accessToken;
  308. }
  309.  
  310. public void setAccessToken(String accessToken) {
  311. this.accessToken = accessToken;
  312. }
  313.  
  314. public Date getDateOfBirth() {
  315. return dateOfBirth;
  316. }
  317.  
  318. public void setDateOfBirth(Date dateOfBirth) {
  319. this.dateOfBirth = dateOfBirth;
  320. }
  321.  
  322. public String getTelephone() {
  323. return telephone;
  324. }
  325.  
  326. public void setTelephone(String telephone) {
  327. this.telephone = telephone;
  328. }
  329.  
  330. public String getCurrentDeviceID() {
  331. return currentDeviceID;
  332. }
  333.  
  334. public void setCurrentDeviceID(String currentDeviceID) {
  335. this.currentDeviceID = currentDeviceID;
  336. }
  337.  
  338. public RealmList<Friendship> getFriends() {
  339. return friends;
  340. }
  341.  
  342. public void addFriend(final Friendship friend) {
  343. friends.add(friend);
  344. }
  345.  
  346. public String getProfileImage() {
  347. return profileImage;
  348. }
  349.  
  350. public void setProfileImage(String profileImage) {
  351. this.profileImage = profileImage;
  352. }
  353.  
  354. public String getProfileImageSignature() {
  355. return profileImageSignature;
  356. }
  357.  
  358. public void setProfileImageSignature(String profileImageSignature) {
  359. this.profileImageSignature = profileImageSignature;
  360. }
  361.  
  362. public void setFriends(RealmList<Friendship> friends) {
  363. this.friends = friends;
  364. }
  365.  
  366. public String getFullProfileImageSignature() {
  367. return fullProfileImageSignature;
  368. }
  369.  
  370. public void setFullProfileImageSignature(String fullProfileImageSignature) {
  371. this.fullProfileImageSignature = fullProfileImageSignature;
  372. }
  373. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement