diff --git a/amplify/backend/api/javatag/schema.graphql b/amplify/backend/api/javatag/schema.graphql index 5a0cea8..dadb55d 100644 --- a/amplify/backend/api/javatag/schema.graphql +++ b/amplify/backend/api/javatag/schema.graphql @@ -14,4 +14,5 @@ type Player @model { isIt: Boolean! lat: Float! lon: Float! + Photo: String } diff --git a/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/mutations.graphql b/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/mutations.graphql index aa8ed08..74936f1 100644 --- a/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/mutations.graphql +++ b/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/mutations.graphql @@ -10,6 +10,7 @@ mutation CreateSession($input: CreateSessionInput!) { isIt lat lon + Photo } nextToken } @@ -29,6 +30,7 @@ mutation UpdateSession($input: UpdateSessionInput!) { isIt lat lon + Photo } nextToken } @@ -48,6 +50,7 @@ mutation DeleteSession($input: DeleteSessionInput!) { isIt lat lon + Photo } nextToken } @@ -73,6 +76,7 @@ mutation CreatePlayer($input: CreatePlayerInput!) { isIt lat lon + Photo } } mutation UpdatePlayer($input: UpdatePlayerInput!) { @@ -92,6 +96,7 @@ mutation UpdatePlayer($input: UpdatePlayerInput!) { isIt lat lon + Photo } } mutation DeletePlayer($input: DeletePlayerInput!) { @@ -111,5 +116,6 @@ mutation DeletePlayer($input: DeletePlayerInput!) { isIt lat lon + Photo } } diff --git a/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/queries.graphql b/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/queries.graphql index 871a1f7..ce402c9 100644 --- a/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/queries.graphql +++ b/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/queries.graphql @@ -10,6 +10,7 @@ query GetSession($id: ID!) { isIt lat lon + Photo } nextToken } @@ -54,6 +55,7 @@ query GetPlayer($id: ID!) { isIt lat lon + Photo } } query ListPlayers( @@ -75,6 +77,7 @@ query ListPlayers( isIt lat lon + Photo } nextToken } diff --git a/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/subscriptions.graphql b/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/subscriptions.graphql index 61bd172..e1d6052 100644 --- a/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/subscriptions.graphql +++ b/app/src/main/graphql/com/amazonaws/amplify/generated/graphql/subscriptions.graphql @@ -10,6 +10,7 @@ subscription OnCreateSession { isIt lat lon + Photo } nextToken } @@ -29,6 +30,7 @@ subscription OnUpdateSession { isIt lat lon + Photo } nextToken } @@ -48,6 +50,7 @@ subscription OnDeleteSession { isIt lat lon + Photo } nextToken } @@ -73,6 +76,7 @@ subscription OnCreatePlayer { isIt lat lon + Photo } } subscription OnUpdatePlayer { @@ -92,6 +96,7 @@ subscription OnUpdatePlayer { isIt lat lon + Photo } } subscription OnDeletePlayer { @@ -111,5 +116,6 @@ subscription OnDeletePlayer { isIt lat lon + Photo } } diff --git a/app/src/main/graphql/schema.json b/app/src/main/graphql/schema.json index 7a4e15e..959af0f 100644 --- a/app/src/main/graphql/schema.json +++ b/app/src/main/graphql/schema.json @@ -381,6 +381,16 @@ }, "defaultValue": null }, + { + "name": "Photo", + "description": null, + "type": { + "kind": "INPUT_OBJECT", + "name": "ModelStringFilterInput", + "ofType": null + }, + "defaultValue": null + }, { "name": "and", "description": null, @@ -978,6 +988,18 @@ }, "isDeprecated": false, "deprecationReason": null + }, + { + "name": "Photo", + "description": null, + "args": [], + "type": { + "kind": "SCALAR", + "name": "String", + "ofType": null + }, + "isDeprecated": false, + "deprecationReason": null } ], "inputFields": null, @@ -1636,6 +1658,16 @@ }, "defaultValue": null }, + { + "name": "Photo", + "description": null, + "type": { + "kind": "SCALAR", + "name": "String", + "ofType": null + }, + "defaultValue": null + }, { "name": "playerSessionId", "description": null, @@ -1711,6 +1743,16 @@ }, "defaultValue": null }, + { + "name": "Photo", + "description": null, + "type": { + "kind": "SCALAR", + "name": "String", + "ofType": null + }, + "defaultValue": null + }, { "name": "playerSessionId", "description": null, diff --git a/app/src/main/java/com/javaawesome/tag/MainActivity.java b/app/src/main/java/com/javaawesome/tag/MainActivity.java index 23080e6..5de57a3 100644 --- a/app/src/main/java/com/javaawesome/tag/MainActivity.java +++ b/app/src/main/java/com/javaawesome/tag/MainActivity.java @@ -1,365 +1,386 @@ -package com.javaawesome.tag; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.AlertDialog; -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.app.ActivityCompat; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.location.Location; -import android.location.LocationManager; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.os.Message; -import android.util.Log; -import android.view.View; -import android.widget.EditText; -import android.widget.Toast; - -import com.amazonaws.amplify.generated.graphql.CreatePlayerMutation; -import com.amazonaws.amplify.generated.graphql.CreateSessionMutation; -import com.amazonaws.amplify.generated.graphql.ListPlayersQuery; -import com.amazonaws.amplify.generated.graphql.ListSessionsQuery; -import com.amazonaws.mobile.client.AWSMobileClient; -import com.amazonaws.mobile.client.Callback; -import com.amazonaws.mobile.client.SignInUIOptions; -import com.amazonaws.mobile.client.UserStateDetails; -import com.amazonaws.mobile.config.AWSConfiguration; -import com.amazonaws.mobileconnectors.appsync.AWSAppSyncClient; -import com.amazonaws.mobileconnectors.appsync.fetcher.AppSyncResponseFetchers; -import com.amazonaws.mobileconnectors.s3.transferutility.TransferService; -import com.apollographql.apollo.GraphQLCall; -import com.apollographql.apollo.api.Response; -import com.apollographql.apollo.exception.ApolloException; -import com.google.android.gms.location.FusedLocationProviderClient; -import com.google.android.gms.location.LocationServices; -import com.google.android.gms.maps.model.LatLng; -import com.google.android.gms.tasks.OnFailureListener; -import com.google.android.gms.tasks.OnSuccessListener; -import java.util.LinkedList; -import java.util.List; -import javax.annotation.Nonnull; -import type.CreatePlayerInput; -import type.CreateSessionInput; -import static android.Manifest.permission.ACCESS_COARSE_LOCATION; -import static android.Manifest.permission.ACCESS_FINE_LOCATION; - -public class MainActivity extends AppCompatActivity implements SessionAdapter.OnSessionInteractionListener { - - private final String TAG = "javatag"; - RecyclerView recyclerNearbySessions; - SessionAdapter sessionAdapter; - List sessions; - AWSAppSyncClient awsAppSyncClient; - FusedLocationProviderClient fusedLocationClient; - String sessionId; - String playerId; - LatLng currentUserLocation; - LocationManager locationManager; - AlertDialog alert; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - getApplicationContext().startService(new Intent(getApplicationContext(), TransferService.class)); - - if (this.checkSelfPermission(ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED || - this.checkSelfPermission(ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 10); - } - - // initialize aws mobile client and check if you are logged in or not - AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback() { - @Override - public void onResult(UserStateDetails result) { - // if the user is signed out, show them the sign in page - if (result.getUserState().toString().equals("SIGNED_OUT")) { - signInUser(); - } - } - - @Override - public void onError(Exception e) { - Log.e(TAG, e.getMessage()); - } - }); - - // connect to AWS - awsAppSyncClient = AWSAppSyncClient.builder() - .context(getApplicationContext()) - .awsConfiguration(new AWSConfiguration(getApplicationContext())) - .build(); - - // initialize client for google location services - fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); - - sessions = new LinkedList<>(); - - // initialize recycler view to display nearby game sessions - // TODO: have recycler view filter sessions by distance to user - recyclerNearbySessions = findViewById(R.id.recycler_nearby_sessions); - recyclerNearbySessions.setLayoutManager(new LinearLayoutManager(this)); - this.sessionAdapter = new SessionAdapter(this.sessions, this); - recyclerNearbySessions.setAdapter(this.sessionAdapter); - } - - @Override - protected void onResume() { - super.onResume(); - Log.i(TAG, "onresume called"); - if (checkGpsStatus()) { - getCurrentUserLocation(); - checkIfPlayerAlreadyExistInDatabase(); - } else { - buildAlertMessageNoGps(); - } - queryAllSessions(); - } - - // Create new game session and go to map page - public void goToMap(View view) { - // TODO: check if player already exist in the database - EditText sessionName = findViewById(R.id.editText_session_name); - Log.i(TAG, "goToMap: "+sessionName.getText()); - if(sessionName.getText().length()>0) { - CreateSessionInput input = CreateSessionInput.builder() - .title(sessionName.getText().toString()) - .lat(currentUserLocation.latitude) - .lon(currentUserLocation.longitude) - .radius(500) - .build(); - CreateSessionMutation createSessionMutation = CreateSessionMutation.builder().input(input).build(); - awsAppSyncClient.mutate(createSessionMutation).enqueue(new GraphQLCall.Callback() { - @Override - public void onResponse(@Nonnull Response response) { - sessionId = response.data().createSession().id(); - Intent goToMapIntent = new Intent(MainActivity.this, MapsActivity.class); - goToMapIntent.putExtra("sessionId", sessionId); - goToMapIntent.putExtra("userID", playerId); - MainActivity.this.startActivity(goToMapIntent); - } - - @Override - public void onFailure(@Nonnull ApolloException e) { - Log.e(TAG, "error in creating new game session" + e.getMessage()); - } - }); - }else{ - Toast.makeText(getBaseContext(), "Please enter a session title.",Toast.LENGTH_LONG).show(); - } - } - - //////// TEST BUTTON ///// - public void onTestyClick(View view) { - startActivity(new Intent(MainActivity.this, NotificationActivity.class)); - } - - ///////////// Turn on Camera /////////////////// - public void goToCameraClass(View view){ - Intent goToCamera = new Intent(this, ShowMeYourFace.class); - this.startActivity(goToCamera); - } - - ///////////// - - // Direct users to sign in page - private void signInUser() { - AWSMobileClient.getInstance().showSignIn(MainActivity.this, - // customize the built in sign in page - SignInUIOptions.builder().backgroundColor(16763080).build(), - new Callback() { - @Override - public void onResult(UserStateDetails result) { - Log.i(TAG, "successfully show signed in page"); - } - - @Override - public void onError(Exception e) { - Log.e(TAG, e.getMessage()); - } - }); - } - - // sign out user and show them sign in page - public void signoutCurrentUser(View view) { - AWSMobileClient.getInstance().signOut(); - signInUser(); - } - - // onclick method for button to join existing game sessions - @Override - public void joinExistingGameSession(ListSessionsQuery.Item session) { - Intent goToMapIntent = new Intent(this, MapsActivity.class); - goToMapIntent.putExtra("sessionId", session.id()); - goToMapIntent.putExtra("userID", playerId); - this.startActivity(goToMapIntent); - } - -// @Override -// public void addPlayerToChosenGame(final ListSessionsQuery.Item session) { -//// Query -// CreatePlayerInput playerInput = CreatePlayerInput.builder() -// .playerSessionId(session.id()) -// .isIt(false) -// .lat(currentUserLocation.latitude) -// .lon(currentUserLocation.longitude) -// .username(AWSMobileClient.getInstance().getUsername()) -// .build(); -// CreatePlayerMutation createPlayerMutation = CreatePlayerMutation.builder().input(playerInput).build(); -// awsAppSyncClient.mutate(createPlayerMutation).enqueue((new GraphQLCall.Callback() { -// @Override -// public void onResponse(@Nonnull Response response) { -// String userID = response.data().createPlayer().id(); -// Log.i(TAG, "player mutation happened! ... inside of a session mutation"); -// Intent goToMapIntent = new Intent(MainActivity.this, MapsActivity.class); -// goToMapIntent.putExtra("sessionId", session.id()); -// goToMapIntent.putExtra("userID", userID); -// Log.i("veach", session.id() + "\n" +userID); -// } -// @Override -// public void onFailure(@Nonnull ApolloException e) { -// Log.i(TAG, "mutation of player failed, boohoo!"); -// } -// })); -// } - - // get all sessions - private void queryAllSessions() { - Log.i(TAG, "query all sessions"); - awsAppSyncClient.query(ListSessionsQuery.builder().build()) - .responseFetcher(AppSyncResponseFetchers.NETWORK_ONLY) - .enqueue(getAllSessionsCallBack); - } - - // Callback to update the list of sessions and recycler view that displays them - private GraphQLCall.Callback getAllSessionsCallBack = new GraphQLCall.Callback() { - @Override - public void onResponse(@Nonnull final Response response) { - Handler h = new Handler(Looper.getMainLooper()) { - @Override - public void handleMessage(Message inputMessage) { - sessions.clear(); - sessions.addAll(response.data().listSessions().items()); - sessionAdapter.notifyDataSetChanged(); - } - }; - h.obtainMessage().sendToTarget(); - } - - @Override - public void onFailure(@Nonnull ApolloException e) { - - } - }; - - // get current user location - private void getCurrentUserLocation() { - Log.i(TAG, "called getCurrentUserLocation"); - fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener() { - @Override - public void onSuccess(final Location location) { - Log.i(TAG, "" + location); - if (location != null) { - new Thread(new Runnable() { - @Override - public void run() { - currentUserLocation = new LatLng(location.getLatitude(), location.getLongitude()); - Log.i(TAG, "playerId in getcurrentUserlocation " + playerId); - if (playerId == null) { - createPlayer(); - } - } - }).run(); - } - } - }).addOnFailureListener(this, new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - Log.e(TAG, e.getMessage()); - } - }); - } - - // TODO: Build onDestroy that deletes user data from DB - - - private void checkIfPlayerAlreadyExistInDatabase() { - awsAppSyncClient.query(ListPlayersQuery.builder().build()) - .responseFetcher(AppSyncResponseFetchers.NETWORK_ONLY) - .enqueue(new GraphQLCall.Callback() { - @Override - public void onResponse(@Nonnull Response response) { - Log.i(TAG, "this is playerID " + playerId); - String playerName = AWSMobileClient.getInstance().getUsername(); - List players = response.data().listPlayers().items(); - for(ListPlayersQuery.Item player : players){ - if(player.username().equals(playerName)){ - Log.i(TAG, "Username match " + playerName + " " + player.id()); - playerId = player.id(); - getCurrentUserLocation(); - return; - } - } - getCurrentUserLocation(); - } - - @Override - public void onFailure(@Nonnull ApolloException e) { - Log.e(TAG, "error in checking if a player already exists in database"); - } - }); - } - - // Make a Player - private void createPlayer() { - CreatePlayerInput input = CreatePlayerInput.builder() - .lat(currentUserLocation.latitude) - .lon(currentUserLocation.longitude) - .username(AWSMobileClient.getInstance().getUsername()) - .isIt(false) - .build(); - CreatePlayerMutation createPlayerMutation = CreatePlayerMutation.builder().input(input).build(); - awsAppSyncClient.mutate(createPlayerMutation).enqueue(new GraphQLCall.Callback() { - @Override - public void onResponse(@Nonnull Response response) { - Log.i(TAG, "created a player"); - playerId = response.data().createPlayer().id(); - } - - @Override - public void onFailure(@Nonnull ApolloException e) { - Log.e(TAG, "error in creating new player"); - } - }); - } - - private boolean checkGpsStatus() { - locationManager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE); - return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); - } - - private void buildAlertMessageNoGps() { - final AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage("Your GPS is disabled, do you want to enable it?") - .setCancelable(false) - .setPositiveButton("Yes", new DialogInterface.OnClickListener() { - public void onClick(final DialogInterface dialog, final int id) { - startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); - } - }) - .setNegativeButton("No", new DialogInterface.OnClickListener() { - public void onClick(final DialogInterface dialog, final int id) { - dialog.cancel(); - } - }); - alert = builder.create(); - alert.show(); - } +package com.javaawesome.tag; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.ActivityCompat; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import android.Manifest; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.location.Location; +import android.location.LocationManager; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.provider.Settings; +import android.util.Log; +import android.view.View; +import android.widget.EditText; +import android.widget.Toast; + +import com.amazonaws.amplify.generated.graphql.CreatePlayerMutation; +import com.amazonaws.amplify.generated.graphql.CreateSessionMutation; +import com.amazonaws.amplify.generated.graphql.ListPlayersQuery; +import com.amazonaws.amplify.generated.graphql.ListSessionsQuery; +import com.amazonaws.mobile.client.AWSMobileClient; +import com.amazonaws.mobile.client.Callback; +import com.amazonaws.mobile.client.SignInUIOptions; +import com.amazonaws.mobile.client.UserStateDetails; +import com.amazonaws.mobile.config.AWSConfiguration; +import com.amazonaws.mobileconnectors.appsync.AWSAppSyncClient; +import com.amazonaws.mobileconnectors.appsync.fetcher.AppSyncResponseFetchers; +import com.amazonaws.mobileconnectors.s3.transferutility.TransferService; +import com.apollographql.apollo.GraphQLCall; +import com.apollographql.apollo.api.Response; +import com.apollographql.apollo.exception.ApolloException; +import com.google.android.gms.location.FusedLocationProviderClient; +import com.google.android.gms.location.LocationServices; +import com.google.android.gms.maps.model.LatLng; +import com.google.android.gms.tasks.OnFailureListener; +import com.google.android.gms.tasks.OnSuccessListener; +import java.util.LinkedList; +import java.util.List; +import javax.annotation.Nonnull; +import type.CreatePlayerInput; +import type.CreateSessionInput; +import static android.Manifest.permission.ACCESS_COARSE_LOCATION; +import static android.Manifest.permission.ACCESS_FINE_LOCATION; + +public class MainActivity extends AppCompatActivity implements SessionAdapter.OnSessionInteractionListener { + + private final String TAG = "javatag"; + RecyclerView recyclerNearbySessions; + SessionAdapter sessionAdapter; + List sessions; + AWSAppSyncClient awsAppSyncClient; + FusedLocationProviderClient fusedLocationClient; + String sessionId; + String playerId; + LatLng currentUserLocation; + LocationManager locationManager; + AlertDialog alert; + private final int distanceForNearbySessions = 1000; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + getApplicationContext().startService(new Intent(getApplicationContext(), TransferService.class)); + + if (this.checkSelfPermission(ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED || + this.checkSelfPermission(ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 10); + } + + // initialize aws mobile client and check if you are logged in or not + AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback() { + @Override + public void onResult(UserStateDetails result) { + // if the user is signed out, show them the sign in page + if (result.getUserState().toString().equals("SIGNED_OUT")) { + signInUser(); + } + } + + @Override + public void onError(Exception e) { + Log.e(TAG, e.getMessage()); + } + }); + + // connect to AWS + awsAppSyncClient = AWSAppSyncClient.builder() + .context(getApplicationContext()) + .awsConfiguration(new AWSConfiguration(getApplicationContext())) + .build(); + + // initialize client for google location services + fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); + + sessions = new LinkedList<>(); + + // initialize recycler view to display nearby game sessions + // TODO: have recycler view filter sessions by distance to user + recyclerNearbySessions = findViewById(R.id.recycler_nearby_sessions); + recyclerNearbySessions.setLayoutManager(new LinearLayoutManager(this)); + this.sessionAdapter = new SessionAdapter(this.sessions, this); + recyclerNearbySessions.setAdapter(this.sessionAdapter); + } + + @Override + protected void onResume() { + super.onResume(); + Log.i(TAG, "onresume called"); + if (checkGpsStatus()) { +// getCurrentUserLocation(); + checkIfPlayerAlreadyExistInDatabase(); + } else { + buildAlertMessageNoGps(); + } + } + + // Create new game session and go to map page + public void goToMap(View view) { + // TODO: check if player already exist in the database + EditText sessionName = findViewById(R.id.editText_session_name); + Log.i(TAG, "goToMap: "+sessionName.getText()); + if(sessionName.getText().length()>0) { + CreateSessionInput input = CreateSessionInput.builder() + .title(sessionName.getText().toString()) + .lat(currentUserLocation.latitude) + .lon(currentUserLocation.longitude) + .radius(500) + .build(); + CreateSessionMutation createSessionMutation = CreateSessionMutation.builder().input(input).build(); + awsAppSyncClient.mutate(createSessionMutation).enqueue(new GraphQLCall.Callback() { + @Override + public void onResponse(@Nonnull Response response) { + sessionId = response.data().createSession().id(); + Intent goToMapIntent = new Intent(MainActivity.this, MapsActivity.class); + goToMapIntent.putExtra("sessionId", sessionId); + goToMapIntent.putExtra("userID", playerId); + MainActivity.this.startActivity(goToMapIntent); + } + + @Override + public void onFailure(@Nonnull ApolloException e) { + Log.e(TAG, "error in creating new game session" + e.getMessage()); + } + }); + }else{ + Toast.makeText(getBaseContext(), "Please enter a session title.",Toast.LENGTH_LONG).show(); + } + } + + //////// TEST BUTTON ///// + public void onTestyClick(View view) { + startActivity(new Intent(MainActivity.this, NotificationActivity.class)); + } + + ///////////// Turn on Camera /////////////////// + public void goToCameraClass(View view){ + Intent goToCamera = new Intent(this, ShowMeYourFace.class); + this.startActivity(goToCamera); + } + + ///////////// + + // Direct users to sign in page + private void signInUser() { + AWSMobileClient.getInstance().showSignIn(MainActivity.this, + // customize the built in sign in page + SignInUIOptions.builder().backgroundColor(16763080).build(), + new Callback() { + @Override + public void onResult(UserStateDetails result) { + Log.i(TAG, "successfully show signed in page"); + } + + @Override + public void onError(Exception e) { + Log.e(TAG, e.getMessage()); + } + }); + } + + // sign out user and show them sign in page + public void signoutCurrentUser(View view) { + AWSMobileClient.getInstance().signOut(); + signInUser(); + } + + // onclick method for button to join existing game sessions + @Override + public void joinExistingGameSession(ListSessionsQuery.Item session) { + Intent goToMapIntent = new Intent(this, MapsActivity.class); + goToMapIntent.putExtra("sessionId", session.id()); + goToMapIntent.putExtra("userID", playerId); + this.startActivity(goToMapIntent); + } + +// @Override +// public void addPlayerToChosenGame(final ListSessionsQuery.Item session) { +//// Query +// CreatePlayerInput playerInput = CreatePlayerInput.builder() +// .playerSessionId(session.id()) +// .isIt(false) +// .lat(currentUserLocation.latitude) +// .lon(currentUserLocation.longitude) +// .username(AWSMobileClient.getInstance().getUsername()) +// .build(); +// CreatePlayerMutation createPlayerMutation = CreatePlayerMutation.builder().input(playerInput).build(); +// awsAppSyncClient.mutate(createPlayerMutation).enqueue((new GraphQLCall.Callback() { +// @Override +// public void onResponse(@Nonnull Response response) { +// String userID = response.data().createPlayer().id(); +// Log.i(TAG, "player mutation happened! ... inside of a session mutation"); +// Intent goToMapIntent = new Intent(MainActivity.this, MapsActivity.class); +// goToMapIntent.putExtra("sessionId", session.id()); +// goToMapIntent.putExtra("userID", userID); +// Log.i("veach", session.id() + "\n" +userID); +// } +// @Override +// public void onFailure(@Nonnull ApolloException e) { +// Log.i(TAG, "mutation of player failed, boohoo!"); +// } +// })); +// } + + // get all sessions + private void queryAllSessions() { + Log.i(TAG, "query all sessions"); + awsAppSyncClient.query(ListSessionsQuery.builder().build()) + .responseFetcher(AppSyncResponseFetchers.NETWORK_ONLY) + .enqueue(getAllSessionsCallBack); + } + + // Callback to update the list of sessions and recycler view that displays them + private GraphQLCall.Callback getAllSessionsCallBack = new GraphQLCall.Callback() { + @Override + public void onResponse(@Nonnull final Response response) { + Handler h = new Handler(Looper.getMainLooper()) { + @Override + public void handleMessage(Message inputMessage) { + sessions.clear(); + List filteredSessions = filterSessionsBasedOnDistance(response.data().listSessions().items()); + sessions.addAll(filteredSessions); + sessionAdapter.notifyDataSetChanged(); + } + }; + h.obtainMessage().sendToTarget(); + } + + @Override + public void onFailure(@Nonnull ApolloException e) { + + } + }; + + // get current user location + private void getCurrentUserLocation() { + Log.i(TAG, "called getCurrentUserLocation"); + fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener() { + @Override + public void onSuccess(final Location location) { + Log.i(TAG, "" + location); + if (location != null) { + new Thread(new Runnable() { + @Override + public void run() { + currentUserLocation = new LatLng(location.getLatitude(), location.getLongitude()); + queryAllSessions(); + Log.i(TAG, "playerId in getcurrentUserlocation " + playerId); + if (playerId == null) { + createPlayer(); + } + } + }).run(); + } + } + }).addOnFailureListener(this, new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + Log.e(TAG, e.getMessage()); + } + }); + } + + // TODO: Build onDestroy that deletes user data from DB + + + private void checkIfPlayerAlreadyExistInDatabase() { + awsAppSyncClient.query(ListPlayersQuery.builder().build()) + .responseFetcher(AppSyncResponseFetchers.NETWORK_ONLY) + .enqueue(new GraphQLCall.Callback() { + @Override + public void onResponse(@Nonnull Response response) { + Log.i(TAG, "this is playerID " + playerId); + String playerName = AWSMobileClient.getInstance().getUsername(); + List players = response.data().listPlayers().items(); + for(ListPlayersQuery.Item player : players){ + if(player.username().equals(playerName)){ + Log.i(TAG, "Username match " + playerName + " " + player.id()); + playerId = player.id(); + getCurrentUserLocation(); + return; + } + } + getCurrentUserLocation(); + } + + @Override + public void onFailure(@Nonnull ApolloException e) { + Log.e(TAG, "error in checking if a player already exists in database"); + } + }); + } + + // Make a Player + private void createPlayer() { + CreatePlayerInput input = CreatePlayerInput.builder() + .lat(currentUserLocation.latitude) + .lon(currentUserLocation.longitude) + .username(AWSMobileClient.getInstance().getUsername()) + .isIt(false) + .build(); + CreatePlayerMutation createPlayerMutation = CreatePlayerMutation.builder().input(input).build(); + awsAppSyncClient.mutate(createPlayerMutation).enqueue(new GraphQLCall.Callback() { + @Override + public void onResponse(@Nonnull Response response) { + Log.i(TAG, "created a player"); + playerId = response.data().createPlayer().id(); + } + + @Override + public void onFailure(@Nonnull ApolloException e) { + Log.e(TAG, "error in creating new player"); + } + }); + } + + // Checks if Gps Location is turned on or not on the user's phone + private boolean checkGpsStatus() { + locationManager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE); + return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); + } + + private void buildAlertMessageNoGps() { + final AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setMessage("Your GPS is disabled, do you want to enable it?") + .setCancelable(false) + .setPositiveButton("Yes", new DialogInterface.OnClickListener() { + public void onClick(final DialogInterface dialog, final int id) { + startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); + } + }) + .setNegativeButton("No", new DialogInterface.OnClickListener() { + public void onClick(final DialogInterface dialog, final int id) { + dialog.cancel(); + } + }); + alert = builder.create(); + alert.show(); + } + + // filter out list of sessions to a smaller list that consist of sessions nearby the player's location + private List filterSessionsBasedOnDistance(List allSessions) { + List filteredSessions = new LinkedList<>(); + for (ListSessionsQuery.Item session : allSessions) { + double distanceBetweenSessionAndPlayer = Utility.distanceBetweenLatLongPoints(currentUserLocation.latitude, + currentUserLocation.longitude, + session.lat(), + session.lon()); + if (distanceBetweenSessionAndPlayer < distanceForNearbySessions) { + filteredSessions.add(session); + } + } + return filteredSessions; + } } \ No newline at end of file diff --git a/app/src/main/java/com/javaawesome/tag/Utility.java b/app/src/main/java/com/javaawesome/tag/Utility.java new file mode 100644 index 0000000..248be99 --- /dev/null +++ b/app/src/main/java/com/javaawesome/tag/Utility.java @@ -0,0 +1,19 @@ +package com.javaawesome.tag; + +public class Utility { + + // Equation is from https://stackoverflow.com/questions/639695/how-to-convert-latitude-or-longitude-to-meters + // convert to two location points to distance between them in meters + protected static double distanceBetweenLatLongPoints(double lat1, double long1, double lat2, double long2) { + // radius of the Earth in km + double R = 6378.137; + double dLat = (lat2 * Math.PI / 180) - (lat1 * Math.PI / 180); + double dLong = (long2 * Math.PI / 180) - (long1 * Math.PI / 180); + double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLong / 2) * Math.sin(dLong / 2); + double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + double d = R * c; + return d * 1000; + } +} diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 9d13e7b..73f7e61 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -92,6 +92,7 @@ android:textSize="18sp" app:layout_constraintBottom_toTopOf="@+id/recycler_nearby_sessions" app:layout_constraintEnd_toEndOf="parent" - app:layout_constraintStart_toStartOf="parent" /> + app:layout_constraintStart_toStartOf="parent" + app:layout_constraintTop_toBottomOf="@+id/goToMapButton" /> \ No newline at end of file