From aa0d71bcea15de9de24a8e6844bd82c69c74dbf5 Mon Sep 17 00:00:00 2001 From: Hazim Bin Ijaz Date: Thu, 15 May 2025 16:24:24 +0500 Subject: [PATCH] Added other stuff --- Assets/OneSignal.meta | 8 + Assets/OneSignal/link.xml | 5 + Assets/OneSignal/link.xml.meta | 7 + Assets/Plugins/Android/mainTemplate.gradle | 2 + .../Plugins/Android/settingsTemplate.gradle | 3 + .../Authentication/GoogleSignInHandler.cs | 336 ++++++++++++++---- .../AndroidResolverDependencies.xml | 4 + 7 files changed, 287 insertions(+), 78 deletions(-) create mode 100644 Assets/OneSignal.meta create mode 100644 Assets/OneSignal/link.xml create mode 100644 Assets/OneSignal/link.xml.meta diff --git a/Assets/OneSignal.meta b/Assets/OneSignal.meta new file mode 100644 index 00000000..1c12a349 --- /dev/null +++ b/Assets/OneSignal.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d391b5a478674034880aba8e3a52b315 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/OneSignal/link.xml b/Assets/OneSignal/link.xml new file mode 100644 index 00000000..68831e9e --- /dev/null +++ b/Assets/OneSignal/link.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Assets/OneSignal/link.xml.meta b/Assets/OneSignal/link.xml.meta new file mode 100644 index 00000000..04cfe80e --- /dev/null +++ b/Assets/OneSignal/link.xml.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 703b35c883a39644a9cc82c85690fcf6 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/Android/mainTemplate.gradle b/Assets/Plugins/Android/mainTemplate.gradle index aadee50e..3e0e023a 100644 --- a/Assets/Plugins/Android/mainTemplate.gradle +++ b/Assets/Plugins/Android/mainTemplate.gradle @@ -14,6 +14,7 @@ dependencies { // Android Resolver Dependencies Start implementation 'androidx.constraintlayout:constraintlayout:2.1.4' // Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml:12 implementation 'com.google.android.gms:play-services-ads:23.2.0' // Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml:7 + implementation 'com.google.android.gms:play-services-auth:20+' // Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml:10 implementation 'com.google.android.gms:play-services-base:18.6.0' // Assets/Firebase/Editor/AppDependencies.xml:17 implementation 'com.google.android.ump:user-messaging-platform:2.2.0' // Assets/GoogleMobileAds/Editor/GoogleUmpDependencies.xml:7 implementation 'com.google.firebase:firebase-analytics:22.4.0' // Assets/Firebase/Editor/AuthDependencies.xml:15 @@ -21,6 +22,7 @@ dependencies { implementation 'com.google.firebase:firebase-auth:23.2.0' // Assets/Firebase/Editor/AuthDependencies.xml:13 implementation 'com.google.firebase:firebase-auth-unity:12.8.0' // Assets/Firebase/Editor/AuthDependencies.xml:20 implementation 'com.google.firebase:firebase-common:21.0.0' // Assets/Firebase/Editor/AppDependencies.xml:13 + implementation 'com.google.signin:google-signin-support:1.0.4' // Assets/GoogleSignIn/Editor/GoogleSignInSupportDependencies.xml:9 implementation 'com.onesignal:OneSignal:5.1.26' // Packages/com.onesignal.unity.android/Editor/OneSignalAndroidDependencies.xml:6 // Android Resolver Dependencies End **DEPS** diff --git a/Assets/Plugins/Android/settingsTemplate.gradle b/Assets/Plugins/Android/settingsTemplate.gradle index 5d7446f1..6e64e153 100644 --- a/Assets/Plugins/Android/settingsTemplate.gradle +++ b/Assets/Plugins/Android/settingsTemplate.gradle @@ -27,6 +27,9 @@ dependencyResolutionManagement { maven { url "https://maven.google.com/" // Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml:7, Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml:12, Assets/GoogleMobileAds/Editor/GoogleUmpDependencies.xml:7 } + maven { + url (unityProjectPath + "/Assets/GoogleSignIn/Editor/m2repository") // Assets/GoogleSignIn/Editor/GoogleSignInSupportDependencies.xml:9 + } mavenLocal() // Android Resolver Repos End flatDir { diff --git a/Assets/Scripts/Authentication/GoogleSignInHandler.cs b/Assets/Scripts/Authentication/GoogleSignInHandler.cs index fa7a44e8..de821da9 100644 --- a/Assets/Scripts/Authentication/GoogleSignInHandler.cs +++ b/Assets/Scripts/Authentication/GoogleSignInHandler.cs @@ -1,48 +1,73 @@ -using System; -using Firebase.Auth; -using Google; using UnityEngine; -using System.Threading.Tasks; -using Firebase.Extensions; +using UnityEngine.UI; +using Google; using PlayFab; using PlayFab.ClientModels; -using UnityEngine.UI; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using OneSignalSDK; +using System.Collections; +using OneSignalSDK.Debug.Models; -public class GoogleSignInHandler : MonoBehaviour +public class GoogleSignInManager : MonoBehaviour { - private FirebaseAuth auth; private GoogleSignInConfiguration configuration; - [SerializeField] private Button googleSignInButton; - [SerializeField] private Button guestLoginButton; - [SerializeField] private Bootstrapper bootstrapper; - private void OnEnable() - { - googleSignInButton.onClick.AddListener(SignInWithGoogle); - guestLoginButton.onClick.AddListener(GuestLogin); - } - - private void OnDisable() - { - googleSignInButton.onClick.RemoveListener(SignInWithGoogle); - guestLoginButton.onClick.RemoveListener(GuestLogin); - } - - void Start() + public Bootstrapper bootstrapper; + public Button googleSignInButton; + public Button guestLoginButton; + + void Awake() { - PlayFabSettings.staticSettings.TitleId = GameConstants.PlayfabTitleId; - auth = FirebaseAuth.DefaultInstance; configuration = new GoogleSignInConfiguration { WebClientId = GameConstants.WebClientID, RequestEmail = true, - RequestAuthCode = true, - RequestIdToken = true + RequestAuthCode = true }; + GoogleSignIn.Configuration = configuration; - GoogleSignIn.DefaultInstance.EnableDebugLogging(true); + Application.quitting += SyncPlayerPrefsToPlayFabOnQuit; + string ons_id = ""; +#if UNITY_ANDROID + ons_id = GameConstants.OSN_Android; +#elif UNITY_IOS + ons_id = GameConstants.OSN_iOS; +#endif + Debug.Log($"Initializing with appId {ons_id}"); + OneSignal.Debug.LogLevel = LogLevel.Debug; + OneSignal.Initialize(ons_id); + } + + void Start() + { + googleSignInButton.onClick.RemoveAllListeners(); + googleSignInButton.onClick.AddListener(SignInWithGoogle); + + guestLoginButton.onClick.RemoveAllListeners(); + guestLoginButton.onClick.AddListener(GuestLogin); + + if (PlayerPrefs.HasKey("PlayFabID") && !PlayerPrefs.HasKey("GuestMode")) + { + Debug.Log("User previously signed in with Google. Attempting silent login..."); + googleSignInButton.gameObject.SetActive(false); + guestLoginButton.gameObject.SetActive(false); + SignInSilently(); + } + else if (PlayerPrefs.HasKey("GuestMode")) + { + Debug.Log("Guest mode previously selected. Letting user choose again."); + googleSignInButton.gameObject.SetActive(true); + guestLoginButton.gameObject.SetActive(true); + } + else + { + Debug.Log("No login info found. Showing login options."); + googleSignInButton.gameObject.SetActive(true); + guestLoginButton.gameObject.SetActive(true); + } } - public void GuestLogin() { Debug.Log("Starting game in Guest Mode..."); @@ -64,85 +89,240 @@ public class GoogleSignInHandler : MonoBehaviour }; PlayFabClientAPI.LoginWithCustomID(request, result => + { + Debug.Log("✅ Guest Login Success! PlayFab ID: " + result.PlayFabId); + SafePlayerPrefs.SetString("PlayFabID", result.PlayFabId); + PlayerPrefs.Save(); + + if (result.NewlyCreated) { - Debug.Log("✅ Guest Login Success! PlayFab ID: " + result.PlayFabId); - SafePlayerPrefs.SetString("PlayFabID", result.PlayFabId); + SafePlayerPrefs.SetInt("NeedsDisplayNameUpload", 1); PlayerPrefs.Save(); + } - if (result.NewlyCreated) - { - SafePlayerPrefs.SetInt("NeedsDisplayNameUpload", 1); - PlayerPrefs.Save(); - } - - bootstrapper.StartGame(); - }, - error => - { - Debug.LogError("❌ Guest PlayFab login failed: " + error.GenerateErrorReport()); - googleSignInButton.gameObject.SetActive(true); - guestLoginButton.gameObject.SetActive(true); - }); + bootstrapper.StartGame(); + }, + error => + { + Debug.LogError("❌ Guest PlayFab login failed: " + error.GenerateErrorReport()); + googleSignInButton.gameObject.SetActive(true); + guestLoginButton.gameObject.SetActive(true); + }); } - - private void SignInWithGoogle() + + public void SignInWithGoogle() { - if (GoogleSignIn.Configuration == null) - { - Debug.LogWarning("Google Sign-In Configuration is not set."); - return; - } + PlayerPrefs.DeleteKey("GuestMode"); + PlayerPrefs.DeleteAll(); + PlayerPrefs.Save(); + + googleSignInButton.interactable = false; + guestLoginButton.interactable = false; GoogleSignIn.DefaultInstance.SignIn().ContinueWith(OnGoogleSignIn); } private void OnGoogleSignIn(Task task) { - if (task.IsFaulted || task.IsCanceled || task.Result == null) + if (task.IsFaulted || task.IsCanceled) { - Debug.LogError("Google Sign-In failed."); + Debug.LogError("Google Sign-In failed: " + task.Exception); + + googleSignInButton.gameObject.SetActive(true); + googleSignInButton.interactable = true; + + guestLoginButton.gameObject.SetActive(true); + guestLoginButton.interactable = true; return; } - // PlayFab uses ServerAuthCode + GoogleSignInUser user = task.Result; + string authCode = user.AuthCode; + SafePlayerPrefs.SetString("GoogleAuthCode", authCode); + PlayerPrefs.Save(); + + LoginToPlayFab(authCode); + } + + private void SignInSilently() + { + Debug.Log("Attempting Google Silent Sign-In..."); + + GoogleSignIn.DefaultInstance.SignInSilently().ContinueWith(task => + { + if (task.IsFaulted || task.IsCanceled) + { + Debug.LogWarning("Silent Sign-In failed. Showing login buttons."); + googleSignInButton.gameObject.SetActive(true); + googleSignInButton.interactable = true; + + guestLoginButton.gameObject.SetActive(true); + guestLoginButton.interactable = true; + return; + } + + GoogleSignInUser user = task.Result; + string authCode = user.AuthCode; + SafePlayerPrefs.SetString("GoogleAuthCode", authCode); + PlayerPrefs.Save(); + + LoginToPlayFab(authCode); + }); + } + + private void LoginToPlayFab(string authCode) + { + PlayFabSettings.staticSettings.TitleId = GameConstants.PlayfabTitleId; var request = new LoginWithGoogleAccountRequest { - TitleId = PlayFabSettings.staticSettings.TitleId, - ServerAuthCode = task.Result.AuthCode, + TitleId = GameConstants.PlayfabTitleId, + ServerAuthCode = authCode, CreateAccount = true }; - Debug.Log($"LoginWithGoogleAccount Title {request.TitleId} AuthCode {request.ServerAuthCode}"); + PlayFabClientAPI.LoginWithGoogleAccount(request, OnPlayFabLoginSuccess, OnPlayFabLoginFailure); - // // Firebase uses ID token - // var firebaseCredential = GoogleAuthProvider.GetCredential(task.Result.IdToken, null); - // FirebaseAuth.DefaultInstance.SignInWithCredentialAsync(firebaseCredential).ContinueWith(authTask => - // { - // if (authTask.IsCompleted && !authTask.IsFaulted) - // { - // Debug.Log("Firebase sign-in successful"); - // - // } - // else - // { - // Debug.LogError("Firebase sign-in failed: " + authTask.Exception); - // } - // }); } + private void OnPlayFabLoginSuccess(LoginResult result) { - Debug.Log("PlayFab Login Success! PlayFab ID: " + result.PlayFabId); + Debug.Log("✅ PlayFab Login Success! PlayFab ID: " + result.PlayFabId); SafePlayerPrefs.SetString("PlayFabID", result.PlayFabId); PlayerPrefs.Save(); - bootstrapper.StartGame(); + + OneSignal.Login(result.PlayFabId); + StartCoroutine(SaveOneSignalPlayerIdToPlayFab()); + + LoadPlayerPrefsFromPlayFab(() => + { + googleSignInButton.gameObject.SetActive(false); + guestLoginButton.gameObject.SetActive(false); + bootstrapper.StartGame(); + }); + } + + private IEnumerator SaveOneSignalPlayerIdToPlayFab() + { + yield return new WaitForSeconds(1f); + + string playerId = OneSignal.User.PushSubscription.Id; + + if (!string.IsNullOrEmpty(playerId)) + { + Debug.Log("✅ Got OneSignal Player ID: " + playerId); + + var request = new UpdateUserDataRequest + { + Data = new Dictionary + { + { "OneSignalPlayerId", playerId } + } + }; + + PlayFabClientAPI.UpdateUserData(request, + result => Debug.Log("✅ Saved OneSignal Player ID to PlayFab"), + error => Debug.LogError("❌ Failed to save OneSignal Player ID: " + error.GenerateErrorReport())); + } + else + { + Debug.LogWarning("⚠️ OneSignal Player ID not available yet."); + } } private void OnPlayFabLoginFailure(PlayFabError error) { - Debug.LogError("PlayFab Login Failed: " + error.GenerateErrorReport()); + Debug.LogError("❌ PlayFab Login Failed: " + error.GenerateErrorReport()); googleSignInButton.gameObject.SetActive(true); googleSignInButton.interactable = true; + + guestLoginButton.gameObject.SetActive(true); + guestLoginButton.interactable = true; } - -} \ No newline at end of file + + private void LoadPlayerPrefsFromPlayFab(Action onComplete) + { + PlayFabClientAPI.GetUserData(new GetUserDataRequest(), result => + { + if (result.Data != null) + { + foreach (var entry in result.Data) + { + string key = entry.Key; + string rawValue = entry.Value.Value; + + if (rawValue.StartsWith("int:") && int.TryParse(rawValue.Substring(4), out int i)) + SafePlayerPrefs.SetInt(key, i); + else if (rawValue.StartsWith("float:") && float.TryParse(rawValue.Substring(6), out float f)) + SafePlayerPrefs.SetFloat(key, f); + else if (rawValue.StartsWith("string:")) + SafePlayerPrefs.SetString(key, rawValue.Substring(7)); + else + SafePlayerPrefs.SetString(key, rawValue); + + PlayerPrefsKeys.RegisterKey(key); + } + PlayerPrefs.Save(); + } + + onComplete?.Invoke(); + }, + error => + { + Debug.LogError("❌ Failed to load SafePlayerPrefs from PlayFab: " + error.GenerateErrorReport()); + onComplete?.Invoke(); + }); + } + + private void SyncPlayerPrefsToPlayFabOnQuit() + { + if (PlayerPrefs.GetInt("GuestMode", 0) == 1) return; + + Dictionary allPrefs = new Dictionary(); + foreach (var key in PlayerPrefsKeys.GetAllKeys()) + { + allPrefs[key] = PlayerPrefs.GetString(key); + } + + var request = new UpdateUserDataRequest + { + Data = allPrefs + }; + + if (PlayFabClientAPI.IsClientLoggedIn()) + { + PlayFabClientAPI.UpdateUserData(request, + result => Debug.Log("✅ Synced SafePlayerPrefs to PlayFab on quit."), + error => Debug.LogError("❌ Failed to sync SafePlayerPrefs: " + error.GenerateErrorReport())); + } + } + + public void SignOut() + { + // 1) Clear PlayFab session in memory + PlayFabClientAPI.ForgetAllCredentials(); + + // 2) Delete every PlayerPref we’ve registered + foreach (var key in PlayerPrefsKeys.GetAllKeys()) + PlayerPrefs.DeleteKey(key); + // Also remove any extra cruft + PlayerPrefs.DeleteKey("GuestMode"); + PlayerPrefs.DeleteKey("GuestCustomID"); + PlayerPrefs.Save(); + + // 3) Sign out of Google + GoogleSignIn.DefaultInstance.SignOut(); + + // 4) Unlink OneSignal from this user + OneSignal.Logout(); + + // 5) Bring back your login buttons + googleSignInButton.gameObject.SetActive(true); + guestLoginButton.gameObject.SetActive(true); + googleSignInButton.interactable = true; + guestLoginButton.interactable = true; + + Debug.Log("✅ User fully signed out."); + } + +} diff --git a/ProjectSettings/AndroidResolverDependencies.xml b/ProjectSettings/AndroidResolverDependencies.xml index 99258fd7..156592dd 100644 --- a/ProjectSettings/AndroidResolverDependencies.xml +++ b/ProjectSettings/AndroidResolverDependencies.xml @@ -2,6 +2,7 @@ androidx.constraintlayout:constraintlayout:2.1.4 com.google.android.gms:play-services-ads:23.2.0 + com.google.android.gms:play-services-auth:20+ com.google.android.gms:play-services-base:18.6.0 com.google.android.ump:user-messaging-platform:2.2.0 com.google.firebase:firebase-analytics:22.4.0 @@ -9,6 +10,7 @@ com.google.firebase:firebase-auth:23.2.0 com.google.firebase:firebase-auth-unity:12.8.0 com.google.firebase:firebase-common:21.0.0 + com.google.signin:google-signin-support:1.0.4 com.onesignal:OneSignal:5.1.26 @@ -16,6 +18,8 @@ Assets/GeneratedLocalRepo/Firebase/m2repository/com/google/firebase/firebase-app-unity/12.8.0/firebase-app-unity-12.8.0.pom Assets/GeneratedLocalRepo/Firebase/m2repository/com/google/firebase/firebase-auth-unity/12.8.0/firebase-auth-unity-12.8.0.aar Assets/GeneratedLocalRepo/Firebase/m2repository/com/google/firebase/firebase-auth-unity/12.8.0/firebase-auth-unity-12.8.0.pom + Assets/GeneratedLocalRepo/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.4/google-signin-support-1.0.4.aar + Assets/GeneratedLocalRepo/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.4/google-signin-support-1.0.4.pom