diff --git a/.gitignore b/.gitignore index aa724b77..ba0375d9 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,6 @@ .externalNativeBuild .cxx local.properties +keystore.properties +*.jks +*.keystore diff --git a/.idea/planningMode.xml b/.idea/planningMode.xml new file mode 100644 index 00000000..f2ea403f --- /dev/null +++ b/.idea/planningMode.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/app/build.gradle.kts b/app/build.gradle.kts index ce1c148b..06dc7bc5 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,3 +1,6 @@ +import java.io.FileInputStream +import java.util.Properties + plugins { alias(libs.plugins.android.application) id("base") @@ -7,6 +10,13 @@ var versionMajor = 4 var versionMinor = 0 var versionPatch = 0 +val keystorePropertiesFile = rootProject.file("keystore.properties") +val keystoreProperties = Properties().apply { + if (keystorePropertiesFile.exists()) { + load (FileInputStream(keystorePropertiesFile)) + } +} + configure { namespace = "com.team3663.scouting_app" compileSdk = 37 @@ -25,6 +35,17 @@ configure { testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } + signingConfigs { + create("release") { + if (keystorePropertiesFile.exists()) { + storeFile = file(keystoreProperties.getProperty("storeFile")) + storePassword = keystoreProperties.getProperty("storePassword") + keyAlias = keystoreProperties.getProperty("keyAlias") + keyPassword = keystoreProperties.getProperty("keyPassword") + } + } + } + buildTypes { getByName("release") { isMinifyEnabled = true @@ -33,6 +54,9 @@ configure { getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro", ) + if (keystorePropertiesFile.exists()) { + signingConfig = signingConfigs.getByName("release") + } } } compileOptions { @@ -40,6 +64,12 @@ configure { targetCompatibility = JavaVersion.VERSION_11 } + packaging { + resources { + excludes += "META-INF/INDEX.LIST" + excludes += "META-INF/DEPENDENCIES" + } + } } base { @@ -48,11 +78,16 @@ base { dependencies { implementation(libs.appcompat) + implementation(libs.documentfile) implementation(libs.material) implementation(libs.activity) implementation(libs.constraintlayout) implementation(libs.qr.generator) implementation(libs.preference) + implementation(libs.google.api.client) + implementation(libs.google.drive.services) + implementation(libs.play.services.auth) + implementation(libs.mssql) testImplementation(libs.junit) androidTestImplementation(libs.ext.junit) androidTestImplementation(libs.espresso.core) diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index 481bb434..cc4461fd 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -18,4 +18,22 @@ # If you keep the line number information, uncomment this to # hide the original source file name. -#-renamesourcefileattribute SourceFile \ No newline at end of file +#-renamesourcefileattribute SourceFile + +-keep class net.sourceforge.jtds.** { *; } +-dontwarn net.sourceforge.jtds.** + +# Google API/Drive client (google-api-client ships no consumer rules and maps JSON via +# reflection on @Key-annotated fields; R8 would otherwise strip/rename them and break uploads). +-keepattributes Signature,*Annotation*,EnclosingMethod +-keep class com.google.api.client.** { *; } +-keep class com.google.api.services.drive.** { *; } +-keepclassmembers class * { @com.google.api.client.util.Key ; } +-dontwarn com.google.api.client.** +-dontwarn com.google.api.services.drive.** +-dontwarn org.apache.http.** +-dontwarn javax.** + +# Gson (used by GsonFactory to (de)serialize the Drive model classes) +-keep class com.google.gson.** { *; } +-dontwarn com.google.gson.** \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index d5ce06dc..c2ef462d 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,7 @@ + diff --git a/app/src/main/java/com/team3663/scouting_app/activities/AppLaunch.java b/app/src/main/java/com/team3663/scouting_app/activities/AppLaunch.java index dfca5d3c..8dcd1003 100644 --- a/app/src/main/java/com/team3663/scouting_app/activities/AppLaunch.java +++ b/app/src/main/java/com/team3663/scouting_app/activities/AppLaunch.java @@ -52,9 +52,7 @@ public class AppLaunch extends AppCompatActivity { // There are no request codes Intent data = result.getData(); if (Objects.requireNonNull(data).getIntExtra(Constants.Settings.RELOAD_DATA_KEY, 0) == 1) { - Globals.MatchList.clearList(); - Globals.MatchList.LoadDataFile(appLaunchBinding.textStatusFile, appLaunchBinding.progressBarFile, appLaunchBinding.textPercentFile, appLaunchBinding.progressBarOverall, appLaunchBinding.textStatusOverall); - appLaunchBinding.textStatusFile.setText(""); + loadDataFiles(); } } }); @@ -259,6 +257,18 @@ private void initDataFiles() { // Output: void // ============================================================================================= private void loadDataFiles() { + // Ensure the loading file objects are visible + appLaunchBinding.progressBarOverall.setVisibility(View.VISIBLE); + appLaunchBinding.progressBarFile.setVisibility(View.VISIBLE); + appLaunchBinding.textStatusOverall.setVisibility(View.VISIBLE); + appLaunchBinding.textPercentOverall.setVisibility(View.VISIBLE); + appLaunchBinding.textStatusFile.setVisibility(View.VISIBLE); + appLaunchBinding.textPercentFile.setVisibility(View.VISIBLE); + appLaunchBinding.butStartScouting.setVisibility(View.INVISIBLE); + appLaunchBinding.imgButSettings.setVisibility(View.INVISIBLE); + appLaunchBinding.butStartScouting.setClickable(false); + appLaunchBinding.imgButSettings.setClickable(false); + // Clear out the lists, just in case _DataFile.clearAllLists(); @@ -291,6 +301,7 @@ public void run() { throw new RuntimeException(e); } + // Hide the loading file objects appLaunchBinding.progressBarOverall.setVisibility(View.INVISIBLE); appLaunchBinding.progressBarFile.setVisibility(View.INVISIBLE); appLaunchBinding.textStatusOverall.setVisibility(View.INVISIBLE); @@ -301,8 +312,6 @@ public void run() { appLaunchBinding.imgButSettings.setVisibility(View.VISIBLE); appLaunchBinding.butStartScouting.setClickable(true); appLaunchBinding.imgButSettings.setClickable(true); - appLaunchBinding.butStartScouting.setVisibility(View.VISIBLE); - appLaunchBinding.imgButSettings.setVisibility(View.VISIBLE); // Erase the status text appLaunchBinding.textStatusFile.setText(""); diff --git a/app/src/main/java/com/team3663/scouting_app/activities/Settings.java b/app/src/main/java/com/team3663/scouting_app/activities/Settings.java index 71e0d8c2..87828432 100644 --- a/app/src/main/java/com/team3663/scouting_app/activities/Settings.java +++ b/app/src/main/java/com/team3663/scouting_app/activities/Settings.java @@ -17,6 +17,7 @@ import com.team3663.scouting_app.databinding.SettingsBinding; import com.team3663.scouting_app.fragments.*; import com.google.android.material.tabs.TabLayoutMediator; +import com.team3663.scouting_app.utility.CPR_Network; public class Settings extends AppCompatActivity { // ============================================================================================= @@ -42,6 +43,9 @@ protected void onCreate(Bundle in_savedInstanceState) { if (Globals.sp == null) Globals.sp = this.getSharedPreferences(getString(R.string.preference_setting_file_key), Context.MODE_PRIVATE); if (Globals.spe == null) Globals.spe = Globals.sp.edit(); + // Set the files downloaded to false when we first get into settings. + CPR_Network.filesDownloaded = false; + adapter = new SettingsPagerAdapter(this); settingsBinding.viewPager.setAdapter(adapter); @@ -53,12 +57,28 @@ protected void onCreate(Bundle in_savedInstanceState) { ).attach(); // Define a Cancel Button - settingsBinding.butCancel.setOnClickListener(view -> finish()); + settingsBinding.butCancel.setOnClickListener(view -> CancelSettings()); // Define a Save Button settingsBinding.butSave.setOnClickListener(view -> SaveSettings()); } + // ============================================================================================= + // Function: CancelSettings + // Description: Cancel any changes made (ignore them) but set the intent to reload the data + // if new files were downloaded. + // Parameters: void + // Output: void + // ============================================================================================= + private void CancelSettings() { + Intent intent = new Intent(); + + if (CPR_Network.filesDownloaded) intent.putExtra(Constants.Settings.RELOAD_DATA_KEY, 1); + + setResult(RESULT_OK, intent); + finish(); + } + // ============================================================================================= // Function: SaveSettings // Description: Save off the settings before closing this activity @@ -70,6 +90,7 @@ private void SaveSettings() { SettingsPage1 fragmentPage1 = adapter.getFragmentPage1(); SettingsPage2 fragmentPage2 = adapter.getFragmentPage2(); SettingsPage3 fragmentPage3 = adapter.getFragmentPage3(); + SettingsPage4 fragmentPage4 = adapter.getFragmentPage4(); // Page1 Settings if (fragmentPage1 != null && fragmentPage1.binding != null) { @@ -92,9 +113,11 @@ private void SaveSettings() { Globals.spe.putString(Constants.Prefs.SCOUTING_TEAM, ScoutingTeam); } - int NumMatches = Integer.parseInt(fragmentPage1.binding.editNumMatches.getText().toString()); - if (NumMatches < 1) NumMatches = 1; - Globals.spe.putInt(Constants.Prefs.NUM_MATCHES, NumMatches); + Globals.CurrentPrefTeamPos = fragmentPage1.binding.spinnerPrefTeamPos.getSelectedItemPosition(); + Globals.spe.putInt(Constants.Prefs.PREF_TEAM_POS, Globals.CurrentPrefTeamPos); + + Globals.CurrentFieldOrientationPos = fragmentPage1.binding.spinnerOrientation.getSelectedItemPosition(); + Globals.spe.putInt(Constants.Prefs.PREF_ORIENTATION, Globals.CurrentFieldOrientationPos); } // Page2 Settings @@ -104,23 +127,18 @@ private void SaveSettings() { Globals.spe.putInt(Constants.Prefs.COLOR_CONTEXT_MENU, ColorId); } - Globals.CurrentPrefTeamPos = fragmentPage2.binding.spinnerPrefTeamPos.getSelectedItemPosition(); - Globals.spe.putInt(Constants.Prefs.PREF_TEAM_POS, Globals.CurrentPrefTeamPos); - int CurrentQRSize = Integer.parseInt(fragmentPage2.binding.editQRSize.getText().toString()); Globals.spe.putInt(Constants.Prefs.QR_SIZE, CurrentQRSize); - Globals.CurrentFieldOrientationPos = fragmentPage2.binding.spinnerOrientation.getSelectedItemPosition(); - Globals.spe.putInt(Constants.Prefs.PREF_ORIENTATION, Globals.CurrentFieldOrientationPos); + int NumMatches = Integer.parseInt(fragmentPage2.binding.editNumMatches.getText().toString()); + if (NumMatches < 1) NumMatches = 1; + Globals.spe.putInt(Constants.Prefs.NUM_MATCHES, NumMatches); } // Page3 Settings if (fragmentPage3 != null && fragmentPage3.binding != null) { Editable userField; - userField = fragmentPage3.binding.editGoogleDrive.getText(); - Globals.spe.putString(Constants.Prefs.GOOGLE_DRIVE, (userField != null) ? userField.toString() : ""); - userField = fragmentPage3.binding.editServer.getText(); Globals.spe.putString(Constants.Prefs.SQL_SERVER, (userField != null) ? userField.toString() : ""); @@ -134,6 +152,19 @@ private void SaveSettings() { Globals.spe.putString(Constants.Prefs.SQL_PASSWORD, (userField != null) ? userField.toString() : ""); } + // Page4 Settings + if (fragmentPage4 != null && fragmentPage4.binding != null) { + Editable userField; + + userField = fragmentPage4.binding.editGoogleUpload.getText(); + Globals.spe.putString(Constants.Prefs.GOOGLE_DRIVE_UPLOAD, (userField != null) ? userField.toString() : ""); + + userField = fragmentPage4.binding.editGoogleDownload.getText(); + Globals.spe.putString(Constants.Prefs.GOOGLE_DRIVE_DOWNLOAD, (userField != null) ? userField.toString() : ""); + + if (CPR_Network.filesDownloaded) intent.putExtra(Constants.Settings.RELOAD_DATA_KEY, 1); + } + Globals.spe.apply(); setResult(RESULT_OK, intent); finish(); diff --git a/app/src/main/java/com/team3663/scouting_app/activities/SubmitData.java b/app/src/main/java/com/team3663/scouting_app/activities/SubmitData.java index c2b44fbb..b21ae616 100644 --- a/app/src/main/java/com/team3663/scouting_app/activities/SubmitData.java +++ b/app/src/main/java/com/team3663/scouting_app/activities/SubmitData.java @@ -18,17 +18,27 @@ import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; +import android.widget.Toast; + import androidx.activity.EdgeToEdge; +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; +import com.google.android.gms.auth.api.signin.GoogleSignIn; +import com.google.android.gms.auth.api.signin.GoogleSignInAccount; +import com.google.android.gms.auth.api.signin.GoogleSignInOptions; +import com.google.android.gms.common.api.ApiException; +import com.google.android.gms.common.api.Scope; import com.team3663.scouting_app.R; import com.team3663.scouting_app.config.Constants; import com.team3663.scouting_app.config.Globals; import com.team3663.scouting_app.databinding.SubmitDataBinding; +import com.team3663.scouting_app.utility.CPR_Network; import com.team3663.scouting_app.utility.Logger; import com.team3663.scouting_app.utility.achievements.Achievements; @@ -48,6 +58,7 @@ public class SubmitData extends AppCompatActivity { private static MediaPlayer media; private ConnectivityManager connectivityManager; private ConnectivityManager.NetworkCallback networkCallback; + private ActivityResultLauncher googleSignInLauncher; @SuppressLint({"SetTextI18n", "MissingInflatedId"}) @Override @@ -63,6 +74,9 @@ protected void onCreate(Bundle in_savedInstanceState) { return insets; }); + // Register the Google sign-in launcher before the activity is STARTED + initGoogleSignIn(); + // Initialize activity components that need the Logger initAchievements(); @@ -79,6 +93,8 @@ protected void onCreate(Bundle in_savedInstanceState) { initMatch(); initQR(); initBluetooth(); + initGoogle(); + initDatabase(); initQuit(); initNext(); initOverride(); @@ -255,9 +271,7 @@ private class AchievementTimerTaskEnd extends TimerTask { @Override public void run() { - SubmitData.this.runOnUiThread(() -> { - animateAchievementEnd(); - }); + SubmitData.this.runOnUiThread(SubmitData.this::animateAchievementEnd); if (isLast) closeAchievements(); } @@ -414,13 +428,30 @@ public void run() { // Output: void // ============================================================================================= private void initMatch() { + submitDataBinding.spinnerMatch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int i, long l) { + // Save off what you selected to be used until changed again + Globals.TransmitMatchNum = Integer.parseInt(submitDataBinding.spinnerMatch.getSelectedItem().toString()); + submitDataBinding.imageGoogleResult.setImageResource(0); + submitDataBinding.imageDatabaseResult.setImageResource(0); + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + } + }); + // Adds the items from the match log files array to the list ArrayAdapter adp_Match = new ArrayAdapter<>(this, R.layout.cpr_spinner, FindMatches()); adp_Match.setDropDownViewResource(R.layout.cpr_spinner_item); submitDataBinding.spinnerMatch.setAdapter(adp_Match); // Set the selection (if there are any) to the latest match (largest value in the list) - if (adp_Match.getCount() > 0) submitDataBinding.spinnerMatch.setSelection(adp_Match.getCount() - 1, true); + if (adp_Match.getCount() > 0) { + submitDataBinding.spinnerMatch.setSelection(adp_Match.getCount() - 1, true); + Globals.TransmitMatchNum = Integer.parseInt(submitDataBinding.spinnerMatch.getSelectedItem().toString()); + } } // ============================================================================================= @@ -505,7 +536,6 @@ private void initBluetooth() { Globals.isPractice = false; Globals.TransmitMatchNum = Integer.parseInt(submitDataBinding.spinnerMatch.getSelectedItem().toString()); - // Intent GoToBluetooth = new Intent(SubmitData.this, Bluetooth.class); // startActivity(GoToBluetooth); @@ -513,6 +543,163 @@ private void initBluetooth() { }); } + // ============================================================================================= + // Function: initGoogle + // Description: Initialize the Google field + // Parameters: void + // Output: void + // ============================================================================================= + private void initGoogle() { + if (!Globals.network.hasActiveInternet()) { + submitDataBinding.butSendGoogle.setEnabled(false); + return; + } + + submitDataBinding.butSendGoogle.setOnClickListener(view -> { + Globals.TransmitMatchNum = Integer.parseInt(submitDataBinding.spinnerMatch.getSelectedItem().toString()); + submitDataBinding.imageGoogleResult.setImageResource(0); + submitDataBinding.butSendGoogle.setEnabled(false); + submitDataBinding.butSendGoogle.setClickable(false); + submitDataBinding.butSendGoogle.setBackgroundColor(getColor(R.color.light_grey)); + + + // If the Drive service is already built this session, upload straight away + if (Globals.network.isDriveServiceReady()) { + Globals.network.uploadToGoogle(this::handleGoogleUploadResult); + return; + } + + // Reuse an existing sign-in if it already granted the Drive scope + Scope driveScope = new Scope(CPR_Network.GOOGLE_DRIVE_SCOPE); + GoogleSignInAccount last = GoogleSignIn.getLastSignedInAccount(this); + if (GoogleSignIn.hasPermissions(last, driveScope)) { + onGoogleSignedIn(last); + return; + } + + // Otherwise start the interactive sign-in / consent flow + GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) + .requestEmail() + .requestScopes(driveScope) + .build(); + googleSignInLauncher.launch(GoogleSignIn.getClient(this, gso).getSignInIntent()); + }); + } + + // ============================================================================================= + // Function: handleGoogleUploadResult + // Description: Handle the result of a Google Drive upload + // Parameters: result the result of the upload + // Output: void + // ============================================================================================= + private void handleGoogleUploadResult(CPR_Network.Result result) { + if (result == CPR_Network.Result.TRANSMISSION_SUCCESS) { + submitDataBinding.imageGoogleResult.setImageResource(R.drawable.checkmark); + } else { + submitDataBinding.imageGoogleResult.setImageResource(R.drawable.x); + } + + submitDataBinding.butSendGoogle.setEnabled(true); + submitDataBinding.butSendGoogle.setClickable(true); + submitDataBinding.butSendGoogle.setBackgroundColor(getColor(R.color.white)); + } + + // ============================================================================================= + // Function: initGoogleSignIn + // Description: Register the launcher that receives the result of the Google sign-in flow. + // Parameters: void + // Output: void + // ============================================================================================= + private void initGoogleSignIn() { + googleSignInLauncher = registerForActivityResult( + new ActivityResultContracts.StartActivityForResult(), + result -> { + try { + GoogleSignInAccount account = GoogleSignIn + .getSignedInAccountFromIntent(result.getData()) + .getResult(ApiException.class); + onGoogleSignedIn(account); + } catch (ApiException e) { + Toast.makeText(this, "Google sign-in failed", Toast.LENGTH_SHORT).show(); + submitDataBinding.imageGoogleResult.setImageResource(R.drawable.x); + } + }); + } + + // ============================================================================================= + // Function: onGoogleSignedIn + // Description: Build the Drive service from the signed-in account and start the upload. + // Parameters: in_account the account returned from Google sign-in + // Output: void + // ============================================================================================= + private void onGoogleSignedIn(GoogleSignInAccount in_account) { + if (in_account == null || in_account.getAccount() == null) { + Toast.makeText(this, "Google sign-in failed", Toast.LENGTH_SHORT).show(); + submitDataBinding.imageGoogleResult.setImageResource(R.drawable.x); + return; + } + + Globals.network.initDriveService(in_account.getAccount()); + Globals.network.uploadToGoogle(this::handleGoogleUploadResult); + } + + // ============================================================================================= + // Function: initDatabase + // Description: Initialize the Database field + // Parameters: void + // Output: void + // ============================================================================================= + private void initDatabase() { + if (!Globals.network.hasActiveInternet()) { + submitDataBinding.butSendDatabase.setEnabled(false); + submitDataBinding.butSendDatabase.setClickable(false); + submitDataBinding.butSendDatabase.setBackgroundColor(getColor(R.color.light_grey)); + return; + } + + submitDataBinding.butSendDatabase.setOnClickListener(view -> { + //Globals.TransmitMatchNum = Integer.parseInt(submitDataBinding.spinnerMatch.getSelectedItem().toString()); + submitDataBinding.butSendDatabase.setEnabled(false); + submitDataBinding.butSendDatabase.setClickable(false); + submitDataBinding.butSendDatabase.setBackgroundColor(getColor(R.color.light_grey)); + submitDataBinding.imageDatabaseResult.setImageResource(0); + + + Globals.network.sendFileToSQLServer(result -> { + submitDataBinding.butSendDatabase.setEnabled(true); + submitDataBinding.butSendDatabase.setClickable(true); + submitDataBinding.butSendDatabase.setBackgroundColor(getColor(R.color.white)); + switch (result) { + case TRANSMISSION_SUCCESS: + Toast.makeText(this, "Successfully transmitted!", Toast.LENGTH_SHORT).show(); + submitDataBinding.imageDatabaseResult.setImageResource(R.drawable.checkmark); + break; + case NO_NETWORK: + Toast.makeText(this, "No network connection", Toast.LENGTH_SHORT).show(); + submitDataBinding.imageDatabaseResult.setImageResource(R.drawable.x); + break; + case HOST_UNREACHABLE: + Toast.makeText(this, "SQL Server is unreachable", Toast.LENGTH_SHORT).show(); + submitDataBinding.imageDatabaseResult.setImageResource(R.drawable.x); + break; + case NO_DATA: + Toast.makeText(this, "No data to send", Toast.LENGTH_SHORT).show(); + submitDataBinding.imageDatabaseResult.setImageResource(R.drawable.x); + break; + case SQL_EXCEPTION: + Toast.makeText(this, "SQL Server Exception", Toast.LENGTH_SHORT).show(); + submitDataBinding.imageDatabaseResult.setImageResource(R.drawable.x); + break; + case TRANSMISSION_FAILURE: + default: + Toast.makeText(this, "Transmission failed", Toast.LENGTH_SHORT).show(); + submitDataBinding.imageDatabaseResult.setImageResource(R.drawable.x); + break; + } + }); + }); + } + // ============================================================================================= // Function: initQuit // Description: Initialize the Quit button diff --git a/app/src/main/java/com/team3663/scouting_app/config/Constants.java b/app/src/main/java/com/team3663/scouting_app/config/Constants.java index 00b4a830..ab92afab 100644 --- a/app/src/main/java/com/team3663/scouting_app/config/Constants.java +++ b/app/src/main/java/com/team3663/scouting_app/config/Constants.java @@ -121,7 +121,8 @@ public static class Prefs { public static final String STORAGE_URI = "StorageURI"; public static final String PREF_ORIENTATION = "PreferredFieldOrientation"; public static final String QR_SIZE = "PreferredQRSize"; - public static final String GOOGLE_DRIVE = "PreferredGoogleDrive"; + public static final String GOOGLE_DRIVE_UPLOAD = "PreferredGoogleDriveUpload"; + public static final String GOOGLE_DRIVE_DOWNLOAD = "PreferredGoogleDriveDownload"; public static final String SQL_SERVER = "PreferredSqlServer"; public static final String SQL_DATABASE = "PreferredSqlDatabase"; public static final String SQL_USER = "PreferredSqlUser"; @@ -132,6 +133,8 @@ public static class Settings { public static final String[] PREF_TEAM_POS = new String[]{"No Preference", "Blue 1", "Blue 2", "Blue 3", "Red 1", "Red 2", "Red 3"}; public static final String[] PREF_FIELD_ORIENTATION = new String[]{"Automatic", "Blue On Left", "Red On Left"}; public static final String RELOAD_DATA_KEY = "ReloadData"; + public static final String DEFAULT_GOOGLE_UPLOAD = "1DB3Dg9N-4zbOxV28Sor-YJrWuoK_OfY8"; + public static final String DEFAULT_GOOGLE_DOWNLOAD = "12up9moFxnuKezANiMV_ocmwmGz4ONA-v"; } public static class AppLaunch { diff --git a/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage1.java b/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage1.java index d95ba990..aea86ace 100644 --- a/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage1.java +++ b/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage1.java @@ -15,6 +15,8 @@ import com.team3663.scouting_app.config.Globals; import com.team3663.scouting_app.databinding.FragmentSettingsPage1Binding; +import java.util.Objects; + public class SettingsPage1 extends Fragment { public FragmentSettingsPage1Binding binding; public int savedCompetitionId; @@ -32,7 +34,8 @@ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceStat initCompetition(); initDevice(); initScoutingTeam(); - initNumMatches(); + initFieldOrientation(); + initPrefTeamPos(); } // ============================================================================================= @@ -43,7 +46,7 @@ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceStat // ============================================================================================= private void initCompetition() { // Adds Competition information to spinner - ArrayAdapter adp_Competition = new ArrayAdapter<>(requireContext(), + ArrayAdapter adp_Competition = new ArrayAdapter<>(requireContext().getApplicationContext(), R.layout.cpr_spinner, Globals.CompetitionList.getCompetitionList()); adp_Competition.setDropDownViewResource(R.layout.cpr_spinner_item); binding.spinnerCompetition.setAdapter(adp_Competition); @@ -74,7 +77,7 @@ public void onNothingSelected(AdapterView parent) {} // ============================================================================================= private void initDevice() { // Adds Device information to spinner - ArrayAdapter adp_Device = new ArrayAdapter<>(requireContext(), + ArrayAdapter adp_Device = new ArrayAdapter<>(requireContext().getApplicationContext(), R.layout.cpr_spinner, Globals.DeviceList.getDeviceList()); adp_Device.setDropDownViewResource(R.layout.cpr_spinner_item); binding.spinnerDevice.setAdapter(adp_Device); @@ -129,14 +132,39 @@ private void initScoutingTeam() { } // ============================================================================================= - // Function: initNumMatches - // Description: Initialize the Number of Matches to Keep field + // Function: initFieldOrientation + // Description: Initialize the Preferred Field Orientation field // Parameters: void // Output: void // ============================================================================================= - private void initNumMatches() { - // Restore number of files to keep from saved preferences - binding.editNumMatches.setText(String.valueOf(Globals.sp.getInt(Constants.Prefs.NUM_MATCHES, 50))); + private void initFieldOrientation() { + // Adds PreferredFieldOrientation information to spinner + ArrayAdapter adp_PrefOrientation = new ArrayAdapter<>(requireContext(), + R.layout.cpr_spinner, Constants.Settings.PREF_FIELD_ORIENTATION); + adp_PrefOrientation.setDropDownViewResource(R.layout.cpr_spinner_item); + binding.spinnerOrientation.setAdapter(adp_PrefOrientation); + + // Set the selection (if there is one) to the saved one + int savedPrefOrientation = Globals.sp.getInt(Constants.Prefs.PREF_ORIENTATION, 0); + binding.spinnerOrientation.setSelection(savedPrefOrientation, true); + } + + // ============================================================================================= + // Function: initPrefTeamPos + // Description: Initialize the Preferred Team Position field + // Parameters: void + // Output: void + // ============================================================================================= + private void initPrefTeamPos() { + // Adds PreferredTeamPosition information to spinner + ArrayAdapter adp_PrefTeamPos = new ArrayAdapter<>(requireContext().getApplicationContext(), + R.layout.cpr_spinner, Constants.Settings.PREF_TEAM_POS); + adp_PrefTeamPos.setDropDownViewResource(R.layout.cpr_spinner_item); + binding.spinnerPrefTeamPos.setAdapter(adp_PrefTeamPos); + + // Set the selection (if there is one) to the saved one + int savedPrefTeamPos = Globals.sp.getInt(Constants.Prefs.PREF_TEAM_POS, 0); + binding.spinnerPrefTeamPos.setSelection(savedPrefTeamPos, true); } @Override diff --git a/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage2.java b/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage2.java index e637f300..9c44e853 100644 --- a/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage2.java +++ b/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage2.java @@ -29,10 +29,9 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initColors(); - initFieldOrientation(); - initPrefTeamPos(); initQRSize(); initShadowMode(); + initNumMatches(); } // ============================================================================================= @@ -43,7 +42,7 @@ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceStat // ============================================================================================= private void initColors() { // Adds Color information to spinner - ArrayAdapter adp_Color = new ArrayAdapter<>(requireContext(), + ArrayAdapter adp_Color = new ArrayAdapter<>(requireContext().getApplicationContext(), R.layout.cpr_spinner, Globals.ColorList.getDescriptionList()); adp_Color.setDropDownViewResource(R.layout.cpr_spinner_item); binding.spinnerColor.setAdapter(adp_Color); @@ -64,42 +63,6 @@ public void onNothingSelected(AdapterView parent) {} }); } - // ============================================================================================= - // Function: initFieldOrientation - // Description: Initialize the Preferred Field Orientation field - // Parameters: void - // Output: void - // ============================================================================================= - private void initFieldOrientation() { - // Adds PreferredFieldOrientation information to spinner - ArrayAdapter adp_PrefOrientation = new ArrayAdapter<>(requireContext(), - R.layout.cpr_spinner, Constants.Settings.PREF_FIELD_ORIENTATION); - adp_PrefOrientation.setDropDownViewResource(R.layout.cpr_spinner_item); - binding.spinnerOrientation.setAdapter(adp_PrefOrientation); - - // Set the selection (if there is one) to the saved one - int savedPrefOrientation = Globals.sp.getInt(Constants.Prefs.PREF_ORIENTATION, 0); - binding.spinnerOrientation.setSelection(savedPrefOrientation, true); - } - - // ============================================================================================= - // Function: initPrefTeamPos - // Description: Initialize the Preferred Team Position field - // Parameters: void - // Output: void - // ============================================================================================= - private void initPrefTeamPos() { - // Adds PreferredTeamPosition information to spinner - ArrayAdapter adp_PrefTeamPos = new ArrayAdapter<>(requireContext(), - R.layout.cpr_spinner, Constants.Settings.PREF_TEAM_POS); - adp_PrefTeamPos.setDropDownViewResource(R.layout.cpr_spinner_item); - binding.spinnerPrefTeamPos.setAdapter(adp_PrefTeamPos); - - // Set the selection (if there is one) to the saved one - int savedPrefTeamPos = Globals.sp.getInt(Constants.Prefs.PREF_TEAM_POS, 0); - binding.spinnerPrefTeamPos.setSelection(savedPrefTeamPos, true); - } - // ============================================================================================= // Function: initQRSize // Description: Initialize the QR Size field @@ -128,6 +91,17 @@ private void initShadowMode() { binding.checkboxShadowMode.setOnCheckedChangeListener((buttonView, isChecked) -> Globals.isShadowMode = isChecked); } + // ============================================================================================= + // Function: initNumMatches + // Description: Initialize the Number of Matches to Keep field + // Parameters: void + // Output: void + // ============================================================================================= + private void initNumMatches() { + // Restore number of files to keep from saved preferences + binding.editNumMatches.setText(String.valueOf(Globals.sp.getInt(Constants.Prefs.NUM_MATCHES, 50))); + } + @Override public void onDestroyView() { super.onDestroyView(); diff --git a/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage3.java b/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage3.java index db706230..263fca20 100644 --- a/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage3.java +++ b/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage3.java @@ -57,7 +57,6 @@ public void onDestroyView() { // Output: void // ============================================================================================= private void initFields() { - binding.editGoogleDrive.setText(Globals.sp.getString(Constants.Prefs.GOOGLE_DRIVE, "1DB3Dg9N-4zbOxV28Sor-YJrWuoK_OfY8")); binding.editServer.setText(Globals.sp.getString(Constants.Prefs.SQL_SERVER, "mssql01.cpr3663.io")); binding.editDatabase.setText(Globals.sp.getString(Constants.Prefs.SQL_DATABASE, "CPR_Scouting_2025")); binding.editUser.setText(Globals.sp.getString(Constants.Prefs.SQL_USER, "CPR_Tablet")); diff --git a/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage4.java b/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage4.java new file mode 100644 index 00000000..3a7640d0 --- /dev/null +++ b/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPage4.java @@ -0,0 +1,304 @@ +package com.team3663.scouting_app.fragments; + +import android.content.Context; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.net.Network; +import android.net.NetworkCapabilities; +import android.net.NetworkRequest; +import android.net.wifi.WifiInfo; +import android.net.wifi.WifiManager; +import android.os.Build; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Toast; + +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; + +import com.google.android.gms.auth.api.signin.GoogleSignIn; +import com.google.android.gms.auth.api.signin.GoogleSignInAccount; +import com.google.android.gms.auth.api.signin.GoogleSignInOptions; +import com.google.android.gms.common.api.ApiException; +import com.google.android.gms.common.api.Scope; +import com.team3663.scouting_app.R; +import com.team3663.scouting_app.config.Constants; +import com.team3663.scouting_app.config.Globals; +import com.team3663.scouting_app.databinding.FragmentSettingsPage4Binding; +import com.team3663.scouting_app.utility.CPR_Network; + +import java.util.Objects; + +public class SettingsPage4 extends Fragment { + public FragmentSettingsPage4Binding binding; + private ConnectivityManager connectivityManager; + private ConnectivityManager.NetworkCallback networkCallback; + private ActivityResultLauncher googleSignInLauncher; + + + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + binding = FragmentSettingsPage4Binding.inflate(inflater, container, false); + return binding.getRoot(); + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + initNetwork(); + initChooseWifi(); + initGoogleSignIn(); + initRefresh(); + initFields(); + } + + @Override + public void onDestroyView() { + super.onDestroyView(); + // Important: Unregister to avoid memory leaks + if (connectivityManager != null && networkCallback != null) { + connectivityManager.unregisterNetworkCallback(networkCallback); + } + } + + // ============================================================================================= + // Function: handleGoogleDownloadResult + // Description: Handle the result of a Google Drive download + // Parameters: result the result of the download + // Output: void + // ============================================================================================= + private void handleGoogleDownloadResult(CPR_Network.Result result) { + if (result == CPR_Network.Result.TRANSMISSION_SUCCESS) { + binding.imageGoogleResult.setImageResource(R.drawable.checkmark); + } else { + binding.imageGoogleResult.setImageResource(R.drawable.x); + } + + binding.butDownload.setEnabled(true); + binding.butDownload.setClickable(true); + binding.butDownload.setBackgroundColor(requireContext().getColor(R.color.white)); + } + + // ============================================================================================= + // Function: initGoogleSignIn + // Description: Register the launcher that receives the result of the Google sign-in flow. + // Parameters: void + // Output: void + // ============================================================================================= + private void initGoogleSignIn() { + googleSignInLauncher = registerForActivityResult( + new ActivityResultContracts.StartActivityForResult(), + result -> { + try { + GoogleSignInAccount account = GoogleSignIn + .getSignedInAccountFromIntent(result.getData()) + .getResult(ApiException.class); + onGoogleSignedIn(account); + } catch (ApiException e) { + Toast.makeText(requireContext().getApplicationContext(), "Google sign-in failed", Toast.LENGTH_SHORT).show(); + binding.imageGoogleResult.setImageResource(R.drawable.x); + } + }); + } + + // ============================================================================================= + // Function: initFields + // Description: Initialize the Fields on the fragment + // Parameters: void + // Output: void + // ============================================================================================= + private void initFields() { + String pref_Upload = Globals.sp.getString(Constants.Prefs.GOOGLE_DRIVE_UPLOAD, ""); + String pref_Download = Globals.sp.getString(Constants.Prefs.GOOGLE_DRIVE_DOWNLOAD, ""); + + // Set up fields. If the Google folders are either empty or happen to match the default, turn on the default checkbox, + // otherwise allow them to be edited. + if (pref_Upload.isEmpty() || pref_Upload.equals(Constants.Settings.DEFAULT_GOOGLE_UPLOAD)) { + binding.editGoogleUpload.setText(Constants.Settings.DEFAULT_GOOGLE_UPLOAD); + binding.butDefaultUpload.setChecked(true); + binding.editGoogleUpload.setEnabled(false); + } else { + binding.editGoogleUpload.setText(pref_Upload); + binding.butDefaultUpload.setChecked(false); + binding.editGoogleUpload.setEnabled(true); + } + + if (pref_Download.isEmpty() || pref_Download.equals(Constants.Settings.DEFAULT_GOOGLE_DOWNLOAD)) { + binding.editGoogleDownload.setText(Constants.Settings.DEFAULT_GOOGLE_DOWNLOAD); + binding.butDefaultDownload.setChecked(true); + binding.editGoogleDownload.setEnabled(false); + } else { + binding.editGoogleDownload.setText(pref_Upload); + binding.butDefaultDownload.setChecked(false); + binding.editGoogleDownload.setEnabled(true); + } + + // If we default the folder, set the checkbox to checked and disable the edit field and set the default folder name + binding.butDefaultUpload.setOnClickListener(view -> { + if (binding.butDefaultUpload.isChecked()) { + binding.editGoogleUpload.setText(Constants.Settings.DEFAULT_GOOGLE_UPLOAD); + binding.editGoogleUpload.setEnabled(false); + } else { + binding.editGoogleUpload.setEnabled(true); + } + }); + + // If we default the folder, set the checkbox to checked and disable the edit field and set the default folder name + binding.butDefaultDownload.setOnClickListener(view -> { + if (binding.butDefaultDownload.isChecked()) { + binding.editGoogleDownload.setText(Constants.Settings.DEFAULT_GOOGLE_DOWNLOAD); + binding.editGoogleDownload.setEnabled(false); + } else { + binding.editGoogleDownload.setEnabled(true); + } + }); + + // Listen for a button click + binding.butDownload.setOnClickListener(view -> { + binding.butDownload.setEnabled(false); + binding.butDownload.setClickable(false); + binding.butDownload.setBackgroundColor(requireContext().getColor(R.color.light_grey)); + + // If the Drive service is already built this session, upload straight away + if (Globals.network.isDriveServiceReady()) { + Globals.network.downloadFromGoogle(this::handleGoogleDownloadResult); + return; + } + + // Reuse an existing sign-in if it already granted the Drive scope + Scope driveScope = new Scope(CPR_Network.GOOGLE_DRIVE_SCOPE); + GoogleSignInAccount last = GoogleSignIn.getLastSignedInAccount(requireContext().getApplicationContext()); + if (GoogleSignIn.hasPermissions(last, driveScope)) { + onGoogleSignedIn(last); + return; + } + + // Otherwise start the interactive sign-in / consent flow + GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) + .requestEmail() + .requestScopes(driveScope) + .build(); + googleSignInLauncher.launch(GoogleSignIn.getClient(requireContext().getApplicationContext(), gso).getSignInIntent()); + + }); + } + + // ============================================================================================= + // Function: onGoogleSignedIn + // Description: Build the Drive service from the signed-in account and start the upload. + // Parameters: in_account the account returned from Google sign-in + // Output: void + // ============================================================================================= + private void onGoogleSignedIn(GoogleSignInAccount in_account) { + if (in_account == null || in_account.getAccount() == null) { + Toast.makeText(requireContext().getApplicationContext(), "Google sign-in failed", Toast.LENGTH_SHORT).show(); + binding.imageGoogleResult.setImageResource(R.drawable.x); + return; + } + + Globals.network.initDriveService(in_account.getAccount()); + Globals.network.downloadFromGoogle(this::handleGoogleDownloadResult); + } + + // ============================================================================================= + // Function: initRefresh + // Description: Initialize the Refresh button + // Parameters: void + // Output: void + // ============================================================================================= + private void initRefresh() { + binding.butRefresh.setOnClickListener(view -> { + if (Globals.network.hasActiveInternet()) { + binding.imageInternet.setVisibility(View.VISIBLE); + } else { + binding.imageInternet.setVisibility(View.INVISIBLE); + } + }); + } + + // ============================================================================================= + // Function: initChooseWifi + // Description: Initialize the ChooseWifi button + // Parameters: void + // Output: void + // ============================================================================================= + private void initChooseWifi() { + binding.butChoose.setOnClickListener(view -> Globals.network.pickWIFI()); + } + + // ============================================================================================= + // Function: updateWifiIcon + // Description: Update the Wi-Fi signal icon with the correct signal strength level + // Parameters: in_level signal strength level + // Output: void + // ============================================================================================= + private void updateWifiIcon(int in_level) { + // You would typically swap icons here based on level + // 0: No signal, 1-4: Signal bars + switch (in_level) { + case 4: binding.imageWifiSignal.setImageResource(R.drawable.wifi_bar_4); break; + case 3: binding.imageWifiSignal.setImageResource(R.drawable.wifi_bar_3); break; + case 2: binding.imageWifiSignal.setImageResource(R.drawable.wifi_bar_2); break; + case 1: binding.imageWifiSignal.setImageResource(R.drawable.wifi_bar_1); break; + default: binding.imageWifiSignal.setImageResource(R.drawable.wifi_bar_0); break; + } + + // check if we have access to the internet + if (Globals.network.hasActiveInternet()) { + binding.imageInternet.setVisibility(View.VISIBLE); + } else { + binding.imageInternet.setVisibility(View.INVISIBLE); + } + } + + // ============================================================================================= + // Function: initNetwork + // Description: Initialize the network related fields and process + // Parameters: void + // Output: void + // ============================================================================================= + private void initNetwork() { + // setup Wi-Fi monitoring + connectivityManager = (ConnectivityManager) requireContext().getSystemService(Context.CONNECTIVITY_SERVICE); + + NetworkRequest networkRequest = new NetworkRequest.Builder() + .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .build(); + + networkCallback = new ConnectivityManager.NetworkCallback() { + @Override + public void onCapabilitiesChanged(@NonNull Network in_network, @NonNull NetworkCapabilities in_capabilities) { + int rssi = 0; + + // On API 31+, WifiInfo is part of the capabilities (requires location permission) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + WifiInfo wifiInfo = (WifiInfo) in_capabilities.getTransportInfo(); + if (wifiInfo != null) rssi = wifiInfo.getRssi(); + } else { + // Fallback for API 30 + WifiManager wm = (WifiManager) requireContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE); + rssi = wm.getConnectionInfo().getRssi(); + } + + // Convert RSSI to a signal level (0 to 4) + int level = WifiManager.calculateSignalLevel(rssi, 5); + + // Update UI on the main thread + requireActivity().runOnUiThread(() -> updateWifiIcon(level)); + } + + @Override + public void onLost(@NonNull Network in_network) { + // Signal lost or Wi-Fi turned off + requireActivity().runOnUiThread(() -> updateWifiIcon(-1)); + } + }; + + connectivityManager.registerNetworkCallback(networkRequest, networkCallback); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPagerAdapter.java b/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPagerAdapter.java index de1e85b7..02bb3913 100644 --- a/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPagerAdapter.java +++ b/app/src/main/java/com/team3663/scouting_app/fragments/SettingsPagerAdapter.java @@ -9,6 +9,7 @@ public class SettingsPagerAdapter extends FragmentStateAdapter { private SettingsPage1 fragmentPage1; private SettingsPage2 fragmentPage2; private SettingsPage3 fragmentPage3; + private SettingsPage4 fragmentPage4; public SettingsPagerAdapter(@NonNull FragmentActivity fragmentActivity) { super(fragmentActivity); @@ -31,14 +32,17 @@ public Fragment createFragment(int position) { fragmentPage3 = new SettingsPage3(); frag = fragmentPage3; break; - } + case 3: + fragmentPage4 = new SettingsPage4(); + frag = fragmentPage4; + break; } return frag; } @Override public int getItemCount() { - return 3; + return 4; } public SettingsPage1 getFragmentPage1() { @@ -50,4 +54,7 @@ public SettingsPage2 getFragmentPage2() { public SettingsPage3 getFragmentPage3() { return fragmentPage3; } + public SettingsPage4 getFragmentPage4() { + return fragmentPage4; + } } \ No newline at end of file diff --git a/app/src/main/java/com/team3663/scouting_app/utility/CPR_Network.java b/app/src/main/java/com/team3663/scouting_app/utility/CPR_Network.java index e42c8f61..d2ec823c 100644 --- a/app/src/main/java/com/team3663/scouting_app/utility/CPR_Network.java +++ b/app/src/main/java/com/team3663/scouting_app/utility/CPR_Network.java @@ -1,19 +1,49 @@ package com.team3663.scouting_app.utility; +import android.accounts.Account; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkCapabilities; +import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.provider.Settings; +import android.widget.Toast; import androidx.annotation.NonNull; +import androidx.documentfile.provider.DocumentFile; +import com.google.api.services.drive.model.File; +import com.google.api.services.drive.model.FileList; +import com.team3663.scouting_app.config.Constants; +import com.team3663.scouting_app.config.Globals; + +import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; +import com.google.api.client.http.InputStreamContent; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.drive.Drive; +import com.google.api.services.drive.DriveScopes; + +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -22,20 +52,34 @@ // Description: Custom class to handle network related tasks. // ============================================================================================= public class CPR_Network { + public static boolean filesDownloaded = false; + // ============================================================================================= // Class Globals // ============================================================================================= private final Context appContext; private final ExecutorService executor; private final Handler mainHandler; + private static final String GOOGLE_TAG = "DriveUploadHelper"; + // drive.file is a non-sensitive scope (no OAuth verification needed). It grants access only to + // files this app creates, which is all we do here: create a file in the shared folder (any + // signed-in account can write to it via the folder's "anyone with the link can edit" grant). + // Note: this scope does NOT allow listing/reading other files in that folder. + public static final String GOOGLE_DRIVE_SCOPE = DriveScopes.DRIVE; + private Drive driveService; // ============================================================================================= // Why a reachability check ended the way it did. // ============================================================================================= public enum Result { - REACHABLE, // socket connected successfully - NO_NETWORK, // device has no active internet-capable network - HOST_UNREACHABLE // network exists, but host:port could not be reached + REACHABLE, // socket connected successfully + NO_NETWORK, // device has no active internet-capable network + HOST_UNREACHABLE, // network exists, but host:port could not be reached + TRANSMISSION_SUCCESS, // data sent successfully + TRANSMISSION_FAILURE, // data send failed + NO_DATA, // no data to send + LOCAL_DIR_DNE, // no local directory exists + SQL_EXCEPTION // SQL error occurred } public interface Callback { @@ -136,7 +180,7 @@ public void shutdown() { // ============================================================================================= // Function: pickWIFI - // Description: Choose new wifi to connect to + // Description: Choose new Wi-Fi to connect to // Parameters: void // Output: void // ============================================================================================= @@ -153,4 +197,480 @@ public void pickWIFI() { appContext.startActivity(GoToSystemWIFI); } } + + // ============================================================================================= + // Function: sendFileToSQLServer + // Description: Asynchronously sends a scouting file to the SQL Server. Callback is on main thread. + // Parameters: in_callback invoked on the main thread with the result + // Output: void + // ============================================================================================= + public void sendFileToSQLServer(@NonNull Callback in_callback) { + executor.execute(() -> { + Result result = sendFileToSQLServerBlocking(); + mainHandler.post(() -> in_callback.onResult(result)); + }); + } + + // ============================================================================================= + // Function: sendFileToSQLServerBlocking + // Description: Synchronous send. Must NOT be called on the main thread. + // Parameters: void + // Output: Result + // ============================================================================================= + @NonNull + public Result sendFileToSQLServerBlocking() { + if (!hasActiveInternet()) { + return Result.NO_NETWORK; + } + + String sql_server = Globals.sp.getString(Constants.Prefs.SQL_SERVER, ""); + String sql_database = Globals.sp.getString(Constants.Prefs.SQL_DATABASE, ""); + String sql_user = Globals.sp.getString(Constants.Prefs.SQL_USER, ""); + String sql_password = Globals.sp.getString(Constants.Prefs.SQL_PASSWORD, ""); + + // Before proceeding, make sure we have settings and a valid connection to the SQL Server + if (sql_server.isEmpty() || sql_database.isEmpty() || sql_user.isEmpty() || sql_password.isEmpty()) { + return Result.TRANSMISSION_FAILURE; + } + + if (!isHostReachable(sql_server, 1433, 3000)) { + return Result.HOST_UNREACHABLE; + } + + String url = "jdbc:sqlserver://" + sql_server + ";database=" + sql_database + ";encrypt=true;trustServerCertificate=true;useBulkCopyForBatchInsert=true;bulkCopyForBatchInsertFireTriggers=true"; + + String sql = "INSERT INTO Load.Scouting_File(Line) VALUES(?)"; + HashMap line_values = getFileAsStringHashMap(); + + // Before proceeding, make sure we have data to send + if (line_values.isEmpty()) { + return Result.NO_DATA; + } + + // On Android the driver must be registered explicitly; auto-discovery is unreliable + try { + Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); + } catch (ClassNotFoundException e) { + return Result.SQL_EXCEPTION; + } + + try (Connection conn = DriverManager.getConnection(url, sql_user, sql_password)) { + conn.setAutoCommit(false); + // Insert the data, line by line + try (java.sql.PreparedStatement ps = conn.prepareStatement(sql)) { + for (String line : line_values.values()) { + ps.setString(1, line); + ps.addBatch(); + } + + ps.executeBatch(); + conn.commit(); + return Result.TRANSMISSION_SUCCESS; + } catch (SQLException e) { + // Rollback the transaction on error + try { + conn.rollback(); + } catch (SQLException ex) { + // ignore + } + return Result.SQL_EXCEPTION; + } + } catch (SQLException e) { + return Result.SQL_EXCEPTION; + } + } + + // ============================================================================================= + // Function: getFileAsStringHashMap + // Description: Reads in the scouting file (defined by Globals) and convert it to a string hashmap + // Parameters: void + // Output: String representing the entire contents of the file + // ============================================================================================= + public HashMap getFileAsStringHashMap() { + String filename = Globals.CurrentCompetitionId + "_" + Globals.TransmitMatchNum + "_" + Globals.CurrentDeviceId + "_" + Globals.TransmitMatchType + ".csv"; + HashMap file_as_hashmap = new HashMap<>(); + String line; + int size = 0; + + try { + // Open up the correct input stream + InputStream is; + DocumentFile df = Globals.output_df.findFile(filename); + assert df != null; + is = appContext.getContentResolver().openInputStream(df.getUri()); + + // Read in the data + BufferedReader br = new BufferedReader(new InputStreamReader(is)); + + while ((line = br.readLine()) != null) { + size++; + file_as_hashmap.put(size, line); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + + // If we made it this far, add the "F" record at the beginning + file_as_hashmap.put(0, "F," + Globals.CurrentCompetitionId + "," + Globals.TransmitMatchNum + "," + Globals.CurrentDeviceId + "," + Globals.TransmitMatchType); + + return file_as_hashmap; + } + + // ============================================================================================= + // Function: initDriveService + // Description: Build the Google Drive service from a signed-in Google account. Must be called + // (with a Drive-scoped account) before uploadToGoogle(). Uploads run as this + // user, so any Drive folder shared with them (including one they don't own) is + // reachable by folder id. + // Parameters: in_account the signed-in Google account with GOOGLE_DRIVE_SCOPE granted + // Output: void + // ============================================================================================= + public void initDriveService(@NonNull Account in_account) { + GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2( + appContext, Collections.singletonList(GOOGLE_DRIVE_SCOPE)); + credential.setSelectedAccount(in_account); + + driveService = new Drive.Builder( + new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + credential) + .setApplicationName("CPR Scouting App") + .build(); + } + + // ============================================================================================= + // Function: isDriveServiceReady + // Description: Has a Drive service been built from a signed-in account yet? + // Parameters: void + // Output: boolean + // ============================================================================================= + public boolean isDriveServiceReady() { + return driveService != null; + } + + // ============================================================================================= + // Function: showToast + // Description: Post a Toast to the main thread (safe to call from a background thread). + // Parameters: in_context context used to build the Toast + // in_message text to display + // in_duration Toast.LENGTH_SHORT or Toast.LENGTH_LONG + // Output: void + // ============================================================================================= + private void showToast(@NonNull Context in_context, @NonNull String in_message) { + mainHandler.post(() -> Toast.makeText(in_context, in_message, Toast.LENGTH_LONG).show()); + } + + // ============================================================================================= + // Function: uploadToGoogle + // Description: Asynchronously copy the file to the shared Google Drive folder. initDriveService() + // must have been called first. Feedback is shown via Toast on the main thread. + // Parameters: in_callback invoked on the main thread with the result + // Output: void + // ============================================================================================= + public void uploadToGoogle(@NonNull Callback in_callback) { + // We must have a Drive service (built from a signed-in account) before we can upload + if (driveService == null) { + showToast(appContext, "Google Upload Failed: Not signed in to Google"); + in_callback.onResult(Result.TRANSMISSION_FAILURE); + return; + } + + final String filename = Globals.CurrentCompetitionId + "_" + Globals.TransmitMatchNum + "_" + Globals.CurrentDeviceId + "_" + Globals.TransmitMatchType + ".csv"; + DocumentFile df = Globals.output_df.findFile(filename); + + // validate the file exists + if (df==null || !df.exists() || !df.isFile()) { + showToast(appContext, "Google Upload Failed: File not found"); + in_callback.onResult(Result.NO_DATA); + return; + } + + final long localSize = df.length(); + final Uri sourceUri = df.getUri(); + + executor.execute(() -> { + try { + // validate connectivity + if (!hasActiveInternet()) { + showToast(appContext, "Google Upload Failed: No Internet Connection"); + mainHandler.post(() -> in_callback.onResult(Result.NO_NETWORK)); + return; + } + + String mimeType = appContext.getContentResolver().getType(sourceUri); + if (mimeType == null) { + showToast(appContext, "Google Upload Failed: File Type Not Found"); + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_FAILURE)); + return; + } + + com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File(); + fileMetadata.setName(filename); + fileMetadata.setParents(Collections.singletonList(Globals.sp.getString(Constants.Prefs.GOOGLE_DRIVE_UPLOAD, ""))); + + InputStream inputStream = appContext.getContentResolver().openInputStream(sourceUri); + if (inputStream == null) { + showToast(appContext, "Google Upload Failed: Unable to open file"); + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_FAILURE)); + return; + } + + InputStreamContent fileContent = new InputStreamContent(mimeType, inputStream); + if (localSize > 0) { + fileContent.setLength(localSize); + } + + // setSupportsAllDrives(true) is required when the parent folder lives in a Shared + // Drive (or was shared to us from another account). + com.google.api.services.drive.model.File uploadedFile = driveService.files() + .create(fileMetadata, fileContent) + .setSupportsAllDrives(true) + .setFields("id, name, size, trashed") + .execute(); + + if (uploadedFile == null) { + showToast(appContext, "Google Upload Failed: Error transferring file"); + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_FAILURE)); + return; + } + + // Validate upload + com.google.api.services.drive.model.File remoteFile = driveService.files() + .get(uploadedFile.getId()) + .setSupportsAllDrives(true) + .setFields("id, size, trashed") + .execute(); + + if (remoteFile == null || remoteFile.getId() == null || Boolean.TRUE.equals(remoteFile.getTrashed())) { + showToast(appContext, "Google Upload Failed: Unable to find remote file"); + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_FAILURE)); + return; + } + + if (remoteFile.getSize() == null || remoteFile.getSize() != localSize) { + showToast(appContext, "Google Upload Failed: File size mismatch"); + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_FAILURE)); + return; + } + + showToast(appContext, "Google Upload Successful"); + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_SUCCESS)); + } + catch (Exception e) { + showToast(appContext, "Google Upload Failed: Exception occurred"); + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_FAILURE)); + } + }); + } + + // ============================================================================================= + // Function: downloadFromGoogle + // Description: Asynchronously copy the files from the shared Google Drive folder. initDriveService() + // must have been called first. Feedback is shown via Toast on the main thread. + // For each remote file: + // - if no local copy exists, download it + // - if a local copy exists and the MD5 checksum matches, skip it + // - if a local copy exists but the MD5 checksum differs, re-download (overwrite) + // Parameters: in_callback invoked on the main thread with the result + // Output: void + // ============================================================================================= + public void downloadFromGoogle(@NonNull Callback in_callback) { + // validate connectivity + if (!hasActiveInternet()) { + showToast(appContext, "Google Download Failed: No Internet Connection"); + mainHandler.post(() -> in_callback.onResult(Result.NO_NETWORK)); + return; + } + + // We must have a Drive service (built from a signed-in account) before we can upload + if (driveService == null) { + showToast(appContext, "Google Download Failed: Not signed in to Google"); + in_callback.onResult(Result.TRANSMISSION_FAILURE); + return; + } + + // Ensure the folder exists + if (!Globals.input_df.exists()) { + showToast(appContext, "Google Download Failed: Local directory not found"); + in_callback.onResult(Result.LOCAL_DIR_DNE); + return; + } + + final String filename = Globals.CurrentCompetitionId + "_" + Globals.TransmitMatchNum + "_" + Globals.CurrentDeviceId + "_" + Globals.TransmitMatchType + ".csv"; + DocumentFile df = Globals.output_df.findFile(filename); + + executor.execute(() -> { + try { + int files_downloaded = 0; + for (File remote : listGoogleFiles()) { + // silently ignore any google native docs (they don't have a checksum) + if (remote.getMd5Checksum() == null) continue; + + String name = remote.getName(); + DocumentFile local = Globals.input_df.findFile(name); + + // if the local file exists but isn't a file, abort + if (local != null && !local.isFile()) { + showToast(appContext, "Google Download Failed: File not found"); + mainHandler.post(() -> in_callback.onResult(Result.NO_DATA)); + return; + } + + // if the local file doesn't exist, download it. + if (local == null || !local.exists()) { + if (downloadOneFileFromGoogle(remote.getId(), name)) files_downloaded++; + else { + showToast(appContext, "Google Download Failed: Error transmitting file " + name); + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_SUCCESS)); + } + continue; + } + + String remoteMD5 = remote.getMd5Checksum(); + String localMD5 = getFileMD5(local); + + // if the checksums differ, download it again + if (!remoteMD5.equalsIgnoreCase(localMD5)) { + if (downloadOneFileFromGoogle(remote.getId(), name)) files_downloaded++; + else { + showToast(appContext, "Google Download Failed: Error transmitting file " + local.getName()); + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_SUCCESS)); + } + } + } + + if (files_downloaded > 0) { + showToast(appContext, "Google Download Successful: " + files_downloaded + " files"); + CPR_Network.filesDownloaded = true; + } + else showToast(appContext, "Google Download: No new files found"); + + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_SUCCESS)); + } + catch (Exception e) { + if (!Objects.equals(e.getMessage(), "No files found")) showToast(appContext, "Google Download Failed: Exception occurred"); + mainHandler.post(() -> in_callback.onResult(Result.TRANSMISSION_FAILURE)); + } + }); + } + + // ============================================================================================= + // Function: downloadOneFileFromGoogle + // Description: download a single file from Google + // Parameters: in_remoteFileId file ID from Google Drive + // in_df local documentFile + // Output: List of Files + // ============================================================================================= + public boolean downloadOneFileFromGoogle(String in_remoteFileId, String in_localFileName) throws IOException { + DocumentFile tmp = Globals.input_df.findFile(in_localFileName + ".part"); + DocumentFile dest = Globals.input_df.findFile(in_localFileName); + + // if the tmp file exists, delete it + if (tmp != null && tmp.exists()) tmp.delete(); + + // create the file + tmp = Globals.input_df.createFile("text/csv", in_localFileName + ".part"); + + if (tmp == null) return false; + + try (OutputStream out = appContext.getContentResolver().openOutputStream(tmp.getUri(), "wt")) { + if (out == null) return false; + + driveService.files().get(in_remoteFileId).executeMediaAndDownloadTo(out); + out.flush(); + } catch (IOException e) { + tmp.delete(); + return false; + } + + // if we fail to delete the local file, abort + if (dest != null && dest.exists() && !dest.delete()) { + tmp.delete(); + return false; + } + + // if we fail to rename the tmp file, abort + if (!tmp.renameTo(in_localFileName)) { + tmp.delete(); + return false; + } + + return true; + } + + // ============================================================================================= + // Function: listGoogleFiles + // Description: Lists all non-trashed files directly inside a GoogleDrive folder + // Parameters: void + // Output: List of Files + // ============================================================================================= + public List listGoogleFiles() throws IOException { + List files = new ArrayList<>(); + String pageToken = null; + String query = "'" + Globals.sp.getString(Constants.Prefs.GOOGLE_DRIVE_DOWNLOAD, "") + "' in parents and trashed = false " + + "and mimeType != 'application/vnd.google-apps.folder'"; + do { + FileList page = driveService.files().list() + .setQ(query) + .setSpaces("drive") + .setFields("nextPageToken, files(id, name, md5Checksum, mimeType, size)") + .setSupportsAllDrives(true) + .setIncludeItemsFromAllDrives(true) + .setPageSize(1000) + .setPageToken(pageToken) + .execute(); + + if (page.getFiles() != null) { + files.addAll(page.getFiles()); + } + + pageToken = page.getNextPageToken(); + } while (pageToken != null); + + if (files.isEmpty()) { + showToast(appContext, "Google Download Failed: No files found"); + throw new IOException("No files found"); + } + + return files; + } + + // ============================================================================================= + // Function: getFileMD5 + // Description: Calculates the MD5 hash of a file. This matches the md5Checksum provided by + // Google Drive metadata. + // Parameters: in_df DocumentFile to hash + // Output: String representing the hex MD5 hash, or null if it fails + // ============================================================================================= + public String getFileMD5(DocumentFile in_df) { + // validate the file exists + if (in_df==null || !in_df.exists() || !in_df.isFile()) { + showToast(appContext, "Local Checksum (MD5) Failed: File not found"); + return ""; + } + + try (InputStream is = appContext.getContentResolver().openInputStream(in_df.getUri())) { + MessageDigest digest = MessageDigest.getInstance("MD5"); + if (is == null) return null; + byte[] buffer = new byte[8192]; + int read; + while ((read = is.read(buffer)) > 0) { + digest.update(buffer, 0, read); + } + byte[] md5sum = digest.digest(); + StringBuilder hexString = new StringBuilder(); + for (byte b : md5sum) { + hexString.append(Character.forDigit((b >> 4) & 0xF, 16)); + hexString.append(Character.forDigit(b & 0xF, 16)); + } + return hexString.toString(); + } catch (NoSuchAlgorithmException e) { + showToast(appContext, "Local Checksum (MD5) Failed: MD5 algorithm unavailable"); + return null; + } + catch (IOException e) { + showToast(appContext, "Local Checksum (MD5) Failed: Unable to read file"); + return null; + } + } } diff --git a/app/src/main/java/com/team3663/scouting_app/utility/Logger.java b/app/src/main/java/com/team3663/scouting_app/utility/Logger.java index bb307c64..fc988f74 100644 --- a/app/src/main/java/com/team3663/scouting_app/utility/Logger.java +++ b/app/src/main/java/com/team3663/scouting_app/utility/Logger.java @@ -12,12 +12,16 @@ import com.team3663.scouting_app.config.Globals; import com.team3663.scouting_app.utility.achievements.Achievements; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.Objects; // ============================================================================================= @@ -546,6 +550,5 @@ public LoggerEventRow(int in_EventId, int in_Time, int in_X, int in_Y, String in if ((Globals.EventLogger != null) && (!Globals.EventLogger.match_log_events.isEmpty())) prev_time = Globals.EventLogger.match_log_events.get(Globals.EventLogger.match_log_events.size() - 1).LogTime; LogTime = Math.max(in_Time, prev_time); } - } } \ No newline at end of file diff --git a/app/src/main/res/drawable/checkmark.xml b/app/src/main/res/drawable/checkmark.xml new file mode 100644 index 00000000..257a5ef1 --- /dev/null +++ b/app/src/main/res/drawable/checkmark.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/field2025.png b/app/src/main/res/drawable/field2025.png deleted file mode 100644 index f634c9c9..00000000 Binary files a/app/src/main/res/drawable/field2025.png and /dev/null differ diff --git a/app/src/main/res/drawable/x.xml b/app/src/main/res/drawable/x.xml new file mode 100644 index 00000000..6afcac9d --- /dev/null +++ b/app/src/main/res/drawable/x.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/layout/fragment_settings_page1.xml b/app/src/main/res/layout/fragment_settings_page1.xml index d521521e..31d00ca5 100644 --- a/app/src/main/res/layout/fragment_settings_page1.xml +++ b/app/src/main/res/layout/fragment_settings_page1.xml @@ -12,6 +12,7 @@ android:layout_width="match_parent" android:layout_height="35dp" android:orientation="horizontal"> + + + + + + + + + + + - + + - + + + + + + + + + + + - + android:text="@string/settings_team_pref" + tools:ignore="RtlSymmetry" /> + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_settings_page2.xml b/app/src/main/res/layout/fragment_settings_page2.xml index 75a910bb..96b2d8cc 100644 --- a/app/src/main/res/layout/fragment_settings_page2.xml +++ b/app/src/main/res/layout/fragment_settings_page2.xml @@ -12,6 +12,7 @@ android:layout_width="match_parent" android:layout_height="35dp" android:orientation="horizontal"> + + + + - + + - - - - - - - - - - - - + tools:ignore="LabelFor" /> - + + + + diff --git a/app/src/main/res/layout/fragment_settings_page3.xml b/app/src/main/res/layout/fragment_settings_page3.xml index 5994ab59..8e0dabb0 100644 --- a/app/src/main/res/layout/fragment_settings_page3.xml +++ b/app/src/main/res/layout/fragment_settings_page3.xml @@ -64,34 +64,6 @@ app:cornerRadius="16dp"/> - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/match.xml b/app/src/main/res/layout/match.xml index 5e635a2b..6eb3d42f 100644 --- a/app/src/main/res/layout/match.xml +++ b/app/src/main/res/layout/match.xml @@ -164,7 +164,7 @@ android:layout_height="fill_parent" android:scaleType="fitXY" android:contentDescription="Shows the field of play" - app:srcCompat="@drawable/field2025" + app:srcCompat="@drawable/field2026" tools:ignore="HardcodedText,MissingConstraints" /> + + + + + + + - - Wi-Fi Connectivity Refresh Choose Wi-Fi - Google Drive ID + Google Upload Folder + Google Download Folder + Download Files SQL Server Name SQL Database SQL User diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 3e910bc5..62c3f066 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,19 +1,19 @@ [versions] -agp = "9.2.1" +agp = "9.3.1" junit = "4.13.2" -junitVersion = "1.2.1" -espressoCore = "3.6.1" -appcompat = "1.7.0" -material = "1.12.0" -activity = "1.9.1" +junitVersion = "1.3.0" +espressoCore = "3.7.0" +appcompat = "1.8.0" +material = "1.14.0" +activity = "1.13.0" qrgenVersion = "4.3.0" -constraintlayout = "2.1.4" -preference = "1.2.0" -viewpager2 = "1.1.0" -mssql-jdbc = "12.7.0" -play-services-auth = "21.5.1" +constraintlayout = "2.2.2" +preference = "1.2.1" google-api-client = "2.9.0" google-drive-v3 = "v3-rev20260405-2.0.0" +play-services-auth = "21.6.0" +documentfile = "1.1.0" +mssql-jdbc="13.5.1.jre11-preview" [libraries] junit = { group = "junit", name = "junit", version.ref = "junit" } @@ -25,11 +25,11 @@ activity = { group = "androidx.activity", name = "activity", version.ref = "acti constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" } preference = { group = "androidx.preference", name = "preference", version.ref = "preference" } qr-generator = { group = "com.journeyapps", name = "zxing-android-embedded", version.ref = "qrgenVersion" } -viewpager2 = { group = "androidx.viewpager2", name = "viewpager2", version.ref = "viewpager2" } -mssql-jdbc = { group = "com.microsoft.sqlserver", name = "mssql-jdbc", version.ref = "mssql-jdbc" } -play-services-auth = { group = "com.google.android.gms", name = "play-services-auth", version.ref = "play-services-auth" } +documentfile = { group = "androidx.documentfile", name = "documentfile", version.ref = "documentfile" } google-api-client = { group = "com.google.api-client", name = "google-api-client-android", version.ref = "google-api-client" } google-drive-services = { group = "com.google.apis", name = "google-api-services-drive", version.ref = "google-drive-v3" } +play-services-auth = { group = "com.google.android.gms", name = "play-services-auth", version.ref = "play-services-auth" } +mssql = { group = "com.microsoft.sqlserver", name = "mssql-jdbc", version.ref = "mssql-jdbc"} [plugins] android-application = { id = "com.android.application", version.ref = "agp" } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c0..b1b8ef56 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index deacf87a..eb84db68 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,9 @@ -#Sun Feb 23 15:18:11 PST 2025 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0c..249efbb0 100644 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,81 +15,114 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 107acd32..a51ec4f5 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,19 +13,22 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem -@rem Gradle startup script for Windows +@rem gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,15 +43,15 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -56,34 +59,24 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 -:mainEnd -if "%OS%"=="Windows_NT" endlocal +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel -:omega +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL%