Advertisement
kanagara

Untitled

Jul 17th, 2020
1,127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.75 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Threading.Tasks;
  4. using System.Web;
  5. using Firebase.Auth;
  6. using Firebase.DynamicLinks;
  7. using Firebase.Extensions;
  8. using Firebase.Functions;
  9. using Firebase.Messaging;
  10. #if !NO_GPGS
  11. using GooglePlayGames;
  12. using GooglePlayGames.BasicApi;
  13. #endif
  14. using UnityEngine;
  15.  
  16. public class AuthManager : Singleton<AuthManager>
  17. {
  18.     protected override bool shouldPersist => true;
  19.     public static Player CurrentPlayer;
  20.  
  21.     private FirebaseAuth _firebaseAuth;
  22.  
  23.     private FirebaseFunctions _firebaseFunctions;
  24.  
  25.     private string referralUserId;
  26.  
  27.     private bool firebaseInitted = false;
  28.    
  29.     void Start () {
  30. #if !NO_GPGS
  31.         PlayGamesPlatform.InitializeInstance(new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false).Build());
  32.         PlayGamesPlatform.Activate();
  33.        
  34. #endif
  35.         _firebaseAuth = FirebaseAuth.DefaultInstance;
  36.         DynamicLinks.DynamicLinkReceived += DynamicLinksOnDynamicLinkReceived;
  37.         FirebaseMessaging.TokenReceived += OnTokenReceived;
  38.         _firebaseFunctions = FirebaseFunctions.DefaultInstance;
  39.        
  40.         SignIn();
  41.     }
  42.  
  43.  
  44.     private void OnTokenReceived(object sender, TokenReceivedEventArgs e)
  45.     {
  46.         Debug.Log("Token recccieved" + e.Token);
  47.         StartCoroutine(PlayerIsNull(() =>
  48.         {
  49.             CurrentPlayer.fcm = e.Token;
  50.             FirebaseDatabaseManager.Instance.UpdateFCM();
  51.         }));
  52.     }
  53.  
  54.     protected override void OnDestroy()
  55.     {
  56.         base.OnDestroy();
  57.         DynamicLinks.DynamicLinkReceived -= DynamicLinksOnDynamicLinkReceived;
  58.     }
  59.  
  60.     private void DynamicLinksOnDynamicLinkReceived(object sender, ReceivedDynamicLinkEventArgs e)
  61.     {
  62.         var query = HttpUtility.ParseQueryString(e.ReceivedDynamicLink.Url.Query);
  63.         var userId = query["userId"];
  64.         Debug.Log("Dynamic link recieved");
  65.         if (!string.IsNullOrEmpty(userId))
  66.         {
  67.             if (!firebaseInitted)
  68.             {
  69.                 Debug.Log("User ID is " + userId);
  70.                 referralUserId = userId;
  71.             }
  72.             else
  73.             {
  74.                 Debug.Log("User ID is " + userId);
  75.                 WriteRefferalDataToUser(userId);
  76.             }
  77.         }
  78.         else Debug.LogError("User ID is null!");
  79.     }
  80.  
  81.     private void WriteRefferalDataToUser(string userReferred)
  82.     {
  83.         StartCoroutine(PlayerIsNull(() => WriteReferralData(userReferred)));
  84.     }
  85.  
  86.     private IEnumerator PlayerIsNull(Action callback)
  87.     {
  88.         yield return new WaitWhile(() =>CurrentPlayer == null);
  89.         callback();
  90.     }
  91.  
  92.     private void WriteReferralData(string userReferred)
  93.     {
  94.         //if (CurrentPlayer.authId == userReferred || CurrentPlayer.referredUsers.Contains(userReferred)) return;
  95.        
  96.         CurrentPlayer.referredByUser = userReferred;
  97.         FirebaseDatabaseManager.Instance.GetPlayerById(userReferred).ContinueWith(x =>
  98.         {
  99.             if (x.IsCompleted)
  100.             {
  101.                 var player = x.Result;
  102.                 player.referredUsers.Add(GetID());
  103.                 FirebaseDatabaseManager.Instance.UpdateReferredUsers(player);
  104.                 FirebaseDatabaseManager.Instance.UpdateReferredByUser(CurrentPlayer);
  105.             }
  106.         });
  107.     }
  108.  
  109.  
  110.     public static string GetID()
  111.     {
  112.         return FirebaseAuth.DefaultInstance.CurrentUser.UserId;
  113.     }
  114.  
  115.     public static string DisplayName()
  116.     {
  117.         return FirebaseAuth.DefaultInstance.CurrentUser.DisplayName;
  118.     }
  119.  
  120.      void SignIn(Action onSuccess = null, Action onFailed = null)
  121.     {
  122.         Social.localUser.Authenticate(success => {
  123.             Debug.Log("Sign in was " + (success ? "Successfull" : "Unsucessfull"));
  124.             if (success)
  125.             {
  126.                 #if !NO_GPGS
  127.                 //If signing in to Play Games was successful, let's get the servers auth code.
  128.                 string authCode = PlayGamesPlatform.Instance.GetServerAuthCode ();
  129.                 if (string.IsNullOrEmpty(authCode))
  130.                 {
  131.                     Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
  132.                     return;
  133.                 }
  134.                 Credential credential = PlayGamesAuthProvider.GetCredential(authCode);
  135.                 //handling iOS logging in.
  136.                 #else
  137.                 #endif
  138.                 SignInWithCredential(credential, onSuccess);
  139.             }
  140.             else
  141.             {
  142.                 EventPool.Invoke(new UserSignInFinished{ Successful = false});
  143.                 Debug.Log("FAILED");
  144.                 onFailed?.Invoke();
  145.             }
  146.         });
  147.     }
  148.  
  149.      private void SignInWithCredential(Credential credential, Action onSuccess)
  150.      {
  151.          _firebaseAuth.SignInWithCredentialAsync(credential).ContinueWith(task =>
  152.          {
  153.              if (task.IsCanceled) {
  154.                  Debug.LogError ("SignInOnClick was canceled.");
  155.                  EventPool.Invoke(new UserSignInFinished{ Successful = false});
  156.                  return;
  157.              }
  158.              if (task.IsFaulted) {
  159.                  Debug.LogError ("SignInOnClick encountered an error: " + task.Exception);
  160.                  EventPool.Invoke(new UserSignInFinished{ Successful = false});
  161.                  return;
  162.              }
  163.              Debug.Log("Logged in" + " refferralUserID" + referralUserId + "FAS");
  164.              onSuccess?.Invoke();
  165.              EventPool.Invoke(new UserSignInFinished{ Successful = true});
  166.              firebaseInitted = true;
  167.              if (!string.IsNullOrEmpty(referralUserId))
  168.              {
  169.                  WriteRefferalDataToUser(referralUserId);
  170.              }
  171.          });
  172.      }
  173.  
  174.  
  175.      #region Achievements
  176.     public static void UnlockAchievement(string id)
  177.     {
  178.         Social.ReportProgress(id, 100, success => { });
  179.     }
  180.  
  181.     public static void IncrementAchievement(string id, int stepsToIncrement)
  182.     {
  183.         PlayGamesPlatform.Instance.IncrementAchievement(id, stepsToIncrement, success => { });
  184.     }
  185.  
  186.     public static void ShowAchievementsUI()
  187.     {
  188.         Social.ShowAchievementsUI();
  189.     }
  190.     #endregion /Achievements
  191.  
  192.     #region Leaderboards
  193.     public static void AddScoreToLeaderboard(string leaderboardId, long score)
  194.     {
  195.         if (!Social.localUser.authenticated) return;
  196.         Social.ReportScore(score, leaderboardId, success => { });
  197.     }
  198.  
  199.     public static void ShowLeaderboardsUI()
  200.     {
  201.         if (!Social.localUser.authenticated)
  202.             Instance.SignIn(Social.ShowLeaderboardUI, () => Debug.LogError("Sign in failed!"));  
  203.         else
  204.             Social.ShowLeaderboardUI();
  205.     }
  206.     #endregion /Leaderboards
  207.  
  208.     #region Dynamic Links
  209.  
  210.       public static DynamicLinkComponents CreateDynamicLinkComponents() {
  211. #if UNITY_5_6_OR_NEWER
  212.       string appIdentifier = Application.identifier;
  213. #else
  214.       string appIdentifier = Application.bundleIdentifier;
  215. #endif
  216.           return new DynamicLinkComponents(
  217.         // The base Link.
  218.         new Uri(GenerateUri()),
  219.         // The dynamic link domain.
  220.         "https://beatcancer.page.link") {
  221.           AndroidParameters = new AndroidParameters(appIdentifier) {
  222.           FallbackUrl = new System.Uri("https://polyspice.com"),
  223.           MinimumVersion = 12,
  224.           PackageName = "com.Polyspice.BeatCancer"
  225.         },
  226.         SocialMetaTagParameters = new Firebase.DynamicLinks.SocialMetaTagParameters() {
  227.           Title = "My App!",
  228.           Description = "My app is awesome!",
  229.         },
  230.       };
  231.       }
  232.  
  233.       private static string GenerateUri()
  234.       {
  235.           return new UriBuilder("https://polyspice.com/beatcancer")
  236.           {
  237.               Query = $"userId={FirebaseAuth.DefaultInstance.CurrentUser.UserId}"
  238.           }.ToString();
  239.       }
  240.  
  241.       public void CopyInviteLinkToClipboard()
  242.       {
  243.           CreateAndDisplayUnguessableShortLinkAsync().ContinueWith(x =>
  244.           {
  245.               if (x.IsCompleted)
  246.               {
  247.                   TextEditor textEditor = new TextEditor();
  248.                   textEditor.text = x.Result.Url.ToString();
  249.                   textEditor.Copy();
  250.                   Debug.Log("Finished");
  251.               }
  252.               else
  253.               {
  254.                   Debug.Log("Error!" + x.Exception?.Message);
  255.               }
  256.           });
  257.       }
  258.      
  259.       public Task<ShortDynamicLink> CreateAndDisplayUnguessableShortLinkAsync() {
  260.           return CreateAndDisplayShortLinkAsync(new DynamicLinkOptions {
  261.               PathLength = DynamicLinkPathLength.Unguessable
  262.           });
  263.       }
  264.  
  265.       private Task<ShortDynamicLink> CreateAndDisplayShortLinkAsync(DynamicLinkOptions options) {
  266.          
  267.           return DynamicLinks.GetShortLinkAsync(CreateDynamicLinkComponents(), options)
  268.               .ContinueWithOnMainThread((task) => {
  269.                   if (task.IsCanceled) {
  270.                       Debug.Log("Short link creation canceled");
  271.                   } else if (task.IsFaulted) {
  272.                       Debug.Log(String.Format("Short link creation failed {0}", task.Exception.ToString()));
  273.                   } else {
  274.                       ShortDynamicLink link = task.Result;
  275.                       Debug.Log(String.Format("Generated short link {0}", link.Url));
  276.                       var warnings = new System.Collections.Generic.List<string>(link.Warnings);
  277.                       if (warnings.Count > 0) {
  278.                           Debug.Log("Warnings:");
  279.                           foreach (var warning in warnings) {
  280.                               Debug.Log("  " + warning);
  281.                           }
  282.                       }
  283.                   }
  284.                   return task.Result;
  285.               });
  286.       }
  287.      
  288.  
  289.     #endregion
  290.  
  291. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement