Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Threading.Tasks;
- using System.Web;
- using Firebase.Auth;
- using Firebase.DynamicLinks;
- using Firebase.Extensions;
- using Firebase.Functions;
- using Firebase.Messaging;
- #if !NO_GPGS
- using GooglePlayGames;
- using GooglePlayGames.BasicApi;
- #endif
- using UnityEngine;
- public class AuthManager : Singleton<AuthManager>
- {
- protected override bool shouldPersist => true;
- public static Player CurrentPlayer;
- private FirebaseAuth _firebaseAuth;
- private FirebaseFunctions _firebaseFunctions;
- private string referralUserId;
- private bool firebaseInitted = false;
- void Start () {
- #if !NO_GPGS
- PlayGamesPlatform.InitializeInstance(new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false).Build());
- PlayGamesPlatform.Activate();
- #endif
- _firebaseAuth = FirebaseAuth.DefaultInstance;
- DynamicLinks.DynamicLinkReceived += DynamicLinksOnDynamicLinkReceived;
- FirebaseMessaging.TokenReceived += OnTokenReceived;
- _firebaseFunctions = FirebaseFunctions.DefaultInstance;
- SignIn();
- }
- private void OnTokenReceived(object sender, TokenReceivedEventArgs e)
- {
- Debug.Log("Token recccieved" + e.Token);
- StartCoroutine(PlayerIsNull(() =>
- {
- CurrentPlayer.fcm = e.Token;
- FirebaseDatabaseManager.Instance.UpdateFCM();
- }));
- }
- protected override void OnDestroy()
- {
- base.OnDestroy();
- DynamicLinks.DynamicLinkReceived -= DynamicLinksOnDynamicLinkReceived;
- }
- private void DynamicLinksOnDynamicLinkReceived(object sender, ReceivedDynamicLinkEventArgs e)
- {
- var query = HttpUtility.ParseQueryString(e.ReceivedDynamicLink.Url.Query);
- var userId = query["userId"];
- Debug.Log("Dynamic link recieved");
- if (!string.IsNullOrEmpty(userId))
- {
- if (!firebaseInitted)
- {
- Debug.Log("User ID is " + userId);
- referralUserId = userId;
- }
- else
- {
- Debug.Log("User ID is " + userId);
- WriteRefferalDataToUser(userId);
- }
- }
- else Debug.LogError("User ID is null!");
- }
- private void WriteRefferalDataToUser(string userReferred)
- {
- StartCoroutine(PlayerIsNull(() => WriteReferralData(userReferred)));
- }
- private IEnumerator PlayerIsNull(Action callback)
- {
- yield return new WaitWhile(() =>CurrentPlayer == null);
- callback();
- }
- private void WriteReferralData(string userReferred)
- {
- //if (CurrentPlayer.authId == userReferred || CurrentPlayer.referredUsers.Contains(userReferred)) return;
- CurrentPlayer.referredByUser = userReferred;
- FirebaseDatabaseManager.Instance.GetPlayerById(userReferred).ContinueWith(x =>
- {
- if (x.IsCompleted)
- {
- var player = x.Result;
- player.referredUsers.Add(GetID());
- FirebaseDatabaseManager.Instance.UpdateReferredUsers(player);
- FirebaseDatabaseManager.Instance.UpdateReferredByUser(CurrentPlayer);
- }
- });
- }
- public static string GetID()
- {
- return FirebaseAuth.DefaultInstance.CurrentUser.UserId;
- }
- public static string DisplayName()
- {
- return FirebaseAuth.DefaultInstance.CurrentUser.DisplayName;
- }
- void SignIn(Action onSuccess = null, Action onFailed = null)
- {
- Social.localUser.Authenticate(success => {
- Debug.Log("Sign in was " + (success ? "Successfull" : "Unsucessfull"));
- if (success)
- {
- #if !NO_GPGS
- //If signing in to Play Games was successful, let's get the servers auth code.
- string authCode = PlayGamesPlatform.Instance.GetServerAuthCode ();
- if (string.IsNullOrEmpty(authCode))
- {
- Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
- return;
- }
- Credential credential = PlayGamesAuthProvider.GetCredential(authCode);
- //handling iOS logging in.
- #else
- #endif
- SignInWithCredential(credential, onSuccess);
- }
- else
- {
- EventPool.Invoke(new UserSignInFinished{ Successful = false});
- Debug.Log("FAILED");
- onFailed?.Invoke();
- }
- });
- }
- private void SignInWithCredential(Credential credential, Action onSuccess)
- {
- _firebaseAuth.SignInWithCredentialAsync(credential).ContinueWith(task =>
- {
- if (task.IsCanceled) {
- Debug.LogError ("SignInOnClick was canceled.");
- EventPool.Invoke(new UserSignInFinished{ Successful = false});
- return;
- }
- if (task.IsFaulted) {
- Debug.LogError ("SignInOnClick encountered an error: " + task.Exception);
- EventPool.Invoke(new UserSignInFinished{ Successful = false});
- return;
- }
- Debug.Log("Logged in" + " refferralUserID" + referralUserId + "FAS");
- onSuccess?.Invoke();
- EventPool.Invoke(new UserSignInFinished{ Successful = true});
- firebaseInitted = true;
- if (!string.IsNullOrEmpty(referralUserId))
- {
- WriteRefferalDataToUser(referralUserId);
- }
- });
- }
- #region Achievements
- public static void UnlockAchievement(string id)
- {
- Social.ReportProgress(id, 100, success => { });
- }
- public static void IncrementAchievement(string id, int stepsToIncrement)
- {
- PlayGamesPlatform.Instance.IncrementAchievement(id, stepsToIncrement, success => { });
- }
- public static void ShowAchievementsUI()
- {
- Social.ShowAchievementsUI();
- }
- #endregion /Achievements
- #region Leaderboards
- public static void AddScoreToLeaderboard(string leaderboardId, long score)
- {
- if (!Social.localUser.authenticated) return;
- Social.ReportScore(score, leaderboardId, success => { });
- }
- public static void ShowLeaderboardsUI()
- {
- if (!Social.localUser.authenticated)
- Instance.SignIn(Social.ShowLeaderboardUI, () => Debug.LogError("Sign in failed!"));
- else
- Social.ShowLeaderboardUI();
- }
- #endregion /Leaderboards
- #region Dynamic Links
- public static DynamicLinkComponents CreateDynamicLinkComponents() {
- #if UNITY_5_6_OR_NEWER
- string appIdentifier = Application.identifier;
- #else
- string appIdentifier = Application.bundleIdentifier;
- #endif
- return new DynamicLinkComponents(
- // The base Link.
- new Uri(GenerateUri()),
- // The dynamic link domain.
- "https://beatcancer.page.link") {
- AndroidParameters = new AndroidParameters(appIdentifier) {
- FallbackUrl = new System.Uri("https://polyspice.com"),
- MinimumVersion = 12,
- PackageName = "com.Polyspice.BeatCancer"
- },
- SocialMetaTagParameters = new Firebase.DynamicLinks.SocialMetaTagParameters() {
- Title = "My App!",
- Description = "My app is awesome!",
- },
- };
- }
- private static string GenerateUri()
- {
- return new UriBuilder("https://polyspice.com/beatcancer")
- {
- Query = $"userId={FirebaseAuth.DefaultInstance.CurrentUser.UserId}"
- }.ToString();
- }
- public void CopyInviteLinkToClipboard()
- {
- CreateAndDisplayUnguessableShortLinkAsync().ContinueWith(x =>
- {
- if (x.IsCompleted)
- {
- TextEditor textEditor = new TextEditor();
- textEditor.text = x.Result.Url.ToString();
- textEditor.Copy();
- Debug.Log("Finished");
- }
- else
- {
- Debug.Log("Error!" + x.Exception?.Message);
- }
- });
- }
- public Task<ShortDynamicLink> CreateAndDisplayUnguessableShortLinkAsync() {
- return CreateAndDisplayShortLinkAsync(new DynamicLinkOptions {
- PathLength = DynamicLinkPathLength.Unguessable
- });
- }
- private Task<ShortDynamicLink> CreateAndDisplayShortLinkAsync(DynamicLinkOptions options) {
- return DynamicLinks.GetShortLinkAsync(CreateDynamicLinkComponents(), options)
- .ContinueWithOnMainThread((task) => {
- if (task.IsCanceled) {
- Debug.Log("Short link creation canceled");
- } else if (task.IsFaulted) {
- Debug.Log(String.Format("Short link creation failed {0}", task.Exception.ToString()));
- } else {
- ShortDynamicLink link = task.Result;
- Debug.Log(String.Format("Generated short link {0}", link.Url));
- var warnings = new System.Collections.Generic.List<string>(link.Warnings);
- if (warnings.Count > 0) {
- Debug.Log("Warnings:");
- foreach (var warning in warnings) {
- Debug.Log(" " + warning);
- }
- }
- }
- return task.Result;
- });
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement