Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.myplaylifeapp.android.myplaylife.Realm.Objects;
- import android.content.Context;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.os.Build;
- import android.support.annotation.NonNull;
- import android.support.v4.content.LocalBroadcastManager;
- import android.util.Log;
- import com.android.volley.Request;
- import com.android.volley.Response;
- import com.android.volley.error.VolleyError;
- import com.google.android.gms.tasks.OnCompleteListener;
- import com.google.android.gms.tasks.Task;
- import com.google.firebase.iid.FirebaseInstanceId;
- import com.google.firebase.iid.InstanceIdResult;
- import com.google.gson.Gson;
- import com.google.gson.annotations.SerializedName;
- import com.myplaylifeapp.android.myplaylife.BuildConfig;
- import com.myplaylifeapp.android.myplaylife.Configuration.APIEndPoint;
- import com.myplaylifeapp.android.myplaylife.Configuration.AppDelegate;
- import com.myplaylifeapp.android.myplaylife.Configuration.ConfigurationManager;
- import com.myplaylifeapp.android.myplaylife.Configuration.DeviceInfo;
- import com.myplaylifeapp.android.myplaylife.Configuration.RequestOperations;
- import com.myplaylifeapp.android.myplaylife.Notifications.MyPlayLifeFirebaseMessagingService;
- import com.myplaylifeapp.android.myplaylife.R;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyDefaultRequest;
- import com.myplaylifeapp.android.myplaylife.VolleyRequests.VolleyGetRequest;
- import com.myplaylifeapp.android.myplaylife.VolleySingleton;
- import org.json.JSONObject;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.UUID;
- import io.realm.Realm;
- import io.realm.RealmList;
- import io.realm.RealmObject;
- import io.realm.annotations.PrimaryKey;
- /**
- * Created by jack on 05/02/2018.
- */
- public class User extends RealmObject {
- @PrimaryKey
- @SerializedName("id")
- private int userID;
- @SerializedName("current_user_id")
- private int currentUserID;
- @SerializedName("email")
- private String email;
- @SerializedName("name")
- private String name;
- @SerializedName("access_token")
- private String accessToken;
- @SerializedName("date_of_birth")
- private Date dateOfBirth;
- @SerializedName("telephone")
- private String telephone;
- @SerializedName("profile_image")
- private String profileImage;
- private String currentDeviceID;
- private String profileImageSignature = UUID.randomUUID().toString();
- private String fullProfileImageSignature = UUID.randomUUID().toString();
- // private String devicePushToken;
- private RealmList<Friendship> friends = new RealmList<>();
- public static void updateUser(Context context) {
- final Map<String, Object> urlParams = new HashMap<>();
- urlParams.put("userID", ConfigurationManager.getInstance().getCurrentUserID());
- String urlString = APIEndPoint.USERS.urlString(urlParams);
- final VolleyGetRequest userRequest = new VolleyGetRequest(urlString, new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(final JSONObject response) {
- try {
- Realm realm = Realm.getDefaultInstance();
- final JSONObject jsonObject = new JSONObject(response.toString());
- final User gsonUser = new Gson().fromJson(jsonObject.toString(), User.class);
- User user = realm.where(User.class).equalTo("userID", gsonUser.getUserID()).findFirst();
- if (user != null) {
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- try {
- User user = realm.where(User.class).equalTo("userID", gsonUser.getUserID()).findFirst();
- user.setCurrentUserID(gsonUser.currentUserID);
- user.setProfileImage(gsonUser.getProfileImage());
- user.setEmail(gsonUser.getEmail());
- user.setName(gsonUser.getName());
- user.setTelephone(gsonUser.getTelephone());
- user.setDateOfBirth(gsonUser.getDateOfBirth());
- realm.insertOrUpdate(user);
- LocalBroadcastManager.getInstance(AppDelegate.getAppContext()).sendBroadcast(new Intent("profilePictureUpdated"));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- } else {
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- realm.insertOrUpdate(gsonUser);
- }
- });
- }
- realm.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- Log.e("GlideImageLoader", "Failed to download user object");
- RequestOperations.getInstance().checkAuthorisation(error);
- }
- });
- VolleySingleton.getInstance(context).addToRequestQueue(userRequest);
- }
- public void uploadDeviceInfo(final Context context, final MyPlayLifeFirebaseMessagingService.TokenUpdatedCallback tokenUpdatedCallback) {
- FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
- int realmUserID = userID;
- @Override
- public void onComplete(@NonNull Task<InstanceIdResult> task) {
- if (!task.isSuccessful()) {
- Log.w("FirebaseID", "getInstanceId failed", task.getException());
- return;
- }
- // realm closed at this point, recreated on new thread to post the device information
- Realm realm = Realm.getDefaultInstance();
- User user = realm.where(User.class).equalTo("userID", realmUserID).findFirst();
- if (user != null) {
- user.postOrPutDeviceInfo(context, task.getResult().getToken(), tokenUpdatedCallback);
- }
- realm.close();
- }
- });
- }
- public void postOrPutDeviceInfo(final Context context, final String deviceToken, final MyPlayLifeFirebaseMessagingService.TokenUpdatedCallback tokenUpdatedCallback) {
- SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
- final int deviceID = sharedPref.getInt(context.getString(R.string.userDeviceIDForUserID_) + userID, 0);
- int postOrPatch;
- String urlString;
- if (deviceID == 0) {
- postOrPatch = Request.Method.POST;
- urlString = APIEndPoint.USER_DEVICES.urlString();
- } else {
- postOrPatch = Request.Method.PATCH;
- urlString = APIEndPoint.USER_DEVICES.urlString() + "/" + deviceID;
- }
- Map<String, String> paramsDict = new HashMap<>();
- paramsDict.put("token", deviceToken);
- paramsDict.put("app_version", BuildConfig.VERSION_NAME);
- paramsDict.put("system_name", "Android");
- paramsDict.put("system_version", Build.VERSION.RELEASE);
- paramsDict.put("device_model", DeviceInfo.getDeviceName());
- JSONObject params = new JSONObject(paramsDict);
- final int realmUserID = userID;
- VolleyDefaultRequest uploadDeviceInfo = new VolleyDefaultRequest(postOrPatch, urlString, params, new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- if (realmUserID != 0) {
- try {
- int deviceID = response.getInt("id");
- SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
- sharedPref.edit().putInt(context.getString(R.string.userDeviceIDForUserID_) + realmUserID, deviceID).apply();
- } catch (Exception exception) {
- Log.d("Exception", "Could Not Save To Shared Preferences");
- }
- }
- if (tokenUpdatedCallback != null) {
- tokenUpdatedCallback.callback(true);
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- RequestOperations.getInstance().volleyErrorHandler(error, context);
- Log.d("Error:", "Failed to connect to server - sending pushToken");
- if (tokenUpdatedCallback != null) {
- tokenUpdatedCallback.callback(false);
- }
- }
- });
- VolleySingleton.getInstance(context).addToRequestQueue(uploadDeviceInfo);
- }
- public void deleteUserDeviceID(final Context context) {
- SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
- int deviceID = sharedPref.getInt(context.getString(R.string.userDeviceIDForUserID_) + userID, 0);
- String urlString = APIEndPoint.USER_DEVICES.urlString() + "/" + deviceID;
- VolleyDefaultRequest deleteDeviceInfo = new VolleyDefaultRequest(Request.Method.DELETE, urlString, null, new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- }
- });
- VolleySingleton.getInstance(context).addToRequestQueue(deleteDeviceInfo);
- }
- public int getUserID() {
- return userID;
- }
- public void setUserID(int userID) {
- this.userID = userID;
- }
- public int getCurrentUserID() {
- return currentUserID;
- }
- public void setCurrentUserID(int currentUserID) {
- this.currentUserID = currentUserID;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getAccessToken() {
- return accessToken;
- }
- public void setAccessToken(String accessToken) {
- this.accessToken = accessToken;
- }
- public Date getDateOfBirth() {
- return dateOfBirth;
- }
- public void setDateOfBirth(Date dateOfBirth) {
- this.dateOfBirth = dateOfBirth;
- }
- public String getTelephone() {
- return telephone;
- }
- public void setTelephone(String telephone) {
- this.telephone = telephone;
- }
- public String getCurrentDeviceID() {
- return currentDeviceID;
- }
- public void setCurrentDeviceID(String currentDeviceID) {
- this.currentDeviceID = currentDeviceID;
- }
- public RealmList<Friendship> getFriends() {
- return friends;
- }
- public void addFriend(final Friendship friend) {
- friends.add(friend);
- }
- public String getProfileImage() {
- return profileImage;
- }
- public void setProfileImage(String profileImage) {
- this.profileImage = profileImage;
- }
- public String getProfileImageSignature() {
- return profileImageSignature;
- }
- public void setProfileImageSignature(String profileImageSignature) {
- this.profileImageSignature = profileImageSignature;
- }
- public void setFriends(RealmList<Friendship> friends) {
- this.friends = friends;
- }
- public String getFullProfileImageSignature() {
- return fullProfileImageSignature;
- }
- public void setFullProfileImageSignature(String fullProfileImageSignature) {
- this.fullProfileImageSignature = fullProfileImageSignature;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement