OneShotOneKill/Assets/Script/UGUI/Title/TitleLoadingUI.cs

404 lines
14 KiB
C#

using AppleAuth;
using CodeStage.AntiCheat.Storage;
//using Firebase.Auth;
//using Google;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
#if UNITY_ANDROID
using UnityEngine.Android;
#endif
public class TitleLoadingUI : MonoBehaviour
{
public TextMeshProUGUI label_version, label_msg, t_proc;
public Slider slider_proc;
public GameObject[] gos_LoginButton; // 애플(0) 구글(1) 게스트(2)
public GameObject go_InputID;
public TMP_InputField Input_ID;
private IAppleAuthManager appleAuthManager;
bool activeButtons, GoLogin, bServerComplete = false, bSreenTouch = false;
int LoginFail = 0;
float Proc_Value;
private void Awake()
{
Application.targetFrameRate = 60;
go_InputID.SetActive(false);
slider_proc.gameObject.SetActive(true);
slider_proc.value = Proc_Value = 0f;
t_proc.text = "0%";
InActive_LoginButton();
}
IEnumerator Start()
{
ServerInfo.Ins.VersionCode = int.Parse(Resources.Load<TextAsset>("VersionCode").text);
label_version.text = DSUtil.Format("{0}({1})", Application.version, ServerInfo.Ins.VersionCode);
label_msg.text = "";
slider_proc.value = 0f;
// 테이블 로딩 기다리기
while (!TableChecker.Ins.CheckAllLoad()) yield return null;
Add_ProcValue(0.1f); // 테이블 로딩 10%
label_msg.text = table_localtext.Ins.Get_Text(1);
yield return StartCoroutine(Title_Mgr.Ins.Co_Check(Add_ProcValue));
#if !UNITY_EDITOR && UNITY_ANDROID && !FGB_OneStore
if (!Application.version.Equals("9.9.9"))
if (Application.installerName != "com.android.vending")
{
Popup.Ins.Set(ePopupType.One, 2,
() => { Application.OpenURL("market://details?id=" + Application.identifier); DSUtil.Quit(); },
() => { Application.OpenURL("market://details?id=" + Application.identifier); DSUtil.Quit(); });
yield break;
}
#endif
#if UNITY_ANDROID
if (!Permission.HasUserAuthorizedPermission("android.permission.POST_NOTIFICATIONS"))
Permission.RequestUserPermission("android.permission.POST_NOTIFICATIONS");
#endif
#if !UNITY_EDITOR
// 파이어 베이스 초기화
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
//FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);
}
else
{
Debug.LogError(DSUtil.Format( "Could not resolve all Firebase dependencies: {0}", dependencyStatus));
// Firebase Unity SDK is not safe to use here.
}
});
#endif
// 인앱 결제 정보 받아오기
label_msg.text = table_localtext.Ins.Get_Text(3);
yield return new WaitForSeconds(0.1f);
Login();
}
void Update()
{
if (Proc_Value > slider_proc.value)
{
slider_proc.value += Time.deltaTime * 0.25f;
if (Proc_Value <= slider_proc.value)
slider_proc.value = Proc_Value;
}
if (this.appleAuthManager != null)
this.appleAuthManager.Update();
if (activeButtons) Active_LoginButton();
if (GoLogin) Login();
if (LoginFail > 0)
{
switch (LoginFail)
{
case 1: // 애플 로그인 실패
Popup.Ins.Set(ePopupType.Two, 116, Login_SigninwithAppleID, Active_LoginButton);
break;
case 2: // 구글 로그인 실패
Popup.Ins.Set(ePopupType.Two, 117, Login_To_GooglePlay, Active_LoginButton);
break;
}
LoginFail = 0;
}
if (bServerComplete && slider_proc.value >= 0.99f && !bSreenTouch)
Set_OnClickScreen();
}
void Add_ProcValue(float add) { Proc_Value += add; }
public void OnChange_SliderValue()
{
t_proc.text = MyText.Get_PercentValueText_100(DSUtil.Get_SliderValue(slider_proc.value));
}
void Active_LoginButton()
{
label_msg.text = table_localtext.Ins.Get_Text(3);
activeButtons = false;
#if FGB_OneStore
DSUtil.InActivateGameObjects(gos_LoginButton, 1);
#else
//DSUtil.ActivateGameObjects(gos_LoginButton);
DSUtil.InActivateGameObjects(gos_LoginButton, 2); // TODO 정인호 : 지금은 게스트만
#endif
}
void InActive_LoginButton()
{
activeButtons = false;
DSUtil.InActivateGameObjects(gos_LoginButton);
}
void Login()
{
GoLogin = false;
#if UNITY_EDITOR
//go_InputID.SetActive(true);
Input_ID.text = PlayerPrefs.GetString(MyValue.OptionKey_UserID, "TestID");
OnClick_DevLogin();
#else
//var type = ObscuredPrefs.GetInt(MyValue.OptionKey_UserType);
//if (type == 0)
//{
// label_msg.text = table_localtext.Ins.Get_Text(121);
// Active_LoginButton();
// this.appleAuthManager = new AppleAuthManager(new PayloadDeserializer());
//}
//else
{
//label_msg.text = table_localtext.Ins.Get_Text(122);
//InActive_LoginButton();
//ServerInfo.Ins.UserID = ObscuredPrefs.GetString(MyValue.OptionKey_UserID);
//Debug.Log("type : " + type + ", ID : " + ServerInfo.Ins.UserID);
ServerInfo.Ins.UserID = SystemInfo.deviceUniqueIdentifier;
ServerInfo.Ins.Login(ServerComplete);
}
#endif
}
public void OnClick_DevLogin()
{
label_msg.text = table_localtext.Ins.Get_Text(3);
go_InputID.SetActive(false);
PlayerPrefs.SetString(MyValue.OptionKey_UserID, Input_ID.text);
ServerInfo.Ins.UserID = Input_ID.text;
ServerInfo.Ins.Login(ServerComplete);
}
public void Login_SigninwithAppleID()
{
InActive_LoginButton();
//FirebaseAuth auth = FirebaseAuth.DefaultInstance;
#if UNITY_ANDROID
//FederatedOAuthProviderData providerData = new FederatedOAuthProviderData();
//providerData.ProviderId = "apple.com";
//providerData.CustomParameters = new Dictionary<string, string>();
//providerData.CustomParameters.Add("language", "ko_KR");
//FederatedOAuthProvider provider = new FederatedOAuthProvider();
//provider.SetProviderData(providerData);
//auth.SignInWithProviderAsync(provider).ContinueWith(task =>
//{
// if (task.IsCanceled)
// {
// Debug.Log("SignInWithProviderAsync was canceled.");
// LoginFail = 1;
// return;
// }
// if (task.IsFaulted)
// {
// LoginFail = 1;
// task.Exception.Handle(e =>
// {
// return true;
// });
// return;
// }
// ObscuredPrefs.SetInt(MyValue.OptionKey_UserType, 1);
// ObscuredPrefs.SetString(MyValue.OptionKey_UserID, task.Result.User.UserId);
// GoLogin = true;
//});
#else
//this.appleAuthManager.LoginWithAppleId(new AppleAuthLoginArgs(LoginOptions.IncludeEmail | LoginOptions.IncludeFullName),
// async credential =>
// {
// try
// {
// var rawNonce = GenerateRandomString(32);
// var nonce = GenerateSHA256NonceFromRawNonce(rawNonce);
// // Obtained credential, cast it to IAppleIDCredential
// var appleIdCredential = credential as IAppleIDCredential;
// var identityToken = Encoding.UTF8.GetString(appleIdCredential.IdentityToken);
// var authorizationCode = Encoding.UTF8.GetString(appleIdCredential.AuthorizationCode);
// var firebaseCredential = OAuthProvider.GetCredential(
// "apple.com",
// identityToken,
// rawNonce,
// authorizationCode);
// await auth.SignInWithCredentialAsync(firebaseCredential);
// ObscuredPrefs.SetInt(MyValue.OptionKey_UserType, 1);
// ObscuredPrefs.SetString(MyValue.OptionKey_UserID, auth.CurrentUser.UserId); // Apple ID가 아닌 Firebase ID
// if (appleIdCredential.FullName != null)
// {
// var myName = appleIdCredential.FullName.ToLocalizedString();
// //ObscuredPrefs.SetString(MyValue.OptionKey_UserNickName, myName); // 애플 검수 시 최초 닉네임 적어야 하는 것 있으면 본인 이름 가져와야하고 클라에 저장해놔야 함
// await auth.CurrentUser.UpdateUserProfileAsync(new UserProfile { DisplayName = myName });
// }
// GoLogin = true;
// }
// catch (AggregateException ex)
// {
// Debug.Log(ex);
// LoginFail = 1;
// }
// catch (Exception ex)
// {
// Debug.Log(ex);
// LoginFail = 1;
// }
// },
// error =>
// {
// // Something went wrong
// var authorizationErrorCode = error.GetAuthorizationErrorCode();
// Debug.Log(authorizationErrorCode);
// LoginFail = 1;
// });
#endif
}
public void Login_To_GooglePlay()
{
InActive_LoginButton();
//if (GoogleSignIn.Configuration == null)
//{ // 설정
// GoogleSignIn.Configuration = new GoogleSignInConfiguration
// {
// RequestIdToken = true,
// RequestEmail = true,
// // Copy this value from the google-service.json file.
// // oauth_client with type == 3
// WebClientId = "555047237522-ric2l62a2lvp2bkbg2qsdg87jungpn3g.apps.googleusercontent.com"
// };
//}
//if (GoogleSignIn.DefaultInstance == null)
//{
// LoginFail = 2;
// return;
//}
//var sign = GoogleSignIn.DefaultInstance.SignIn();
//if (sign == null)
//{
// LoginFail = 2;
// return;
//}
//sign.ContinueWith(task =>
//{
// if (task == null)
// {
// LoginFail = 2;
// return;
// }
// if (!task.IsCanceled && !task.IsFaulted)
// {
// ObscuredPrefs.SetInt(MyValue.OptionKey_UserType, 2);
// ObscuredPrefs.SetString(MyValue.OptionKey_UserID, task.Result.UserId);
// GoLogin = true;
// }
// else
// LoginFail = 2;
//});
}
public void Login_SigninwithGuest()
{
Popup.Ins.Set(ePopupType.Two, 123,
() =>
{
ObscuredPrefs.SetInt(MyValue.OptionKey_UserType, 4);
ObscuredPrefs.SetString(MyValue.OptionKey_UserID, SystemInfo.deviceUniqueIdentifier);
Login();
}, null);
}
void ServerComplete(bool _newuser)
{
bServerComplete = true;
}
void Set_OnClickScreen()
{
bSreenTouch = true;
label_msg.text = table_localtext.Ins.Get_Text(4);
label_msg.gameObject.AddComponent<TextAlphaPingPong>();
}
public void OnClick_Screen()
{
if (bSreenTouch)
{
//LoadingUI.Ins.Start_Loading();
label_msg.text = "";
SceneManager.LoadScene("02_Game");
}
}
void LoadingEnd()
{
//SceneManager.LoadScene(eScene.InGame.ToString());
//LoadingUI.Ins.End_UI();
}
private string GenerateRandomString(int length)
{
const string charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._";
var cryptographicallySecureRandomNumberGenerator = new RNGCryptoServiceProvider();
var result = string.Empty;
var remainingLength = length;
var randomNumberHolder = new byte[1];
while (remainingLength > 0)
{
var randomNumbers = new List<int>(16);
for (var randomNumberCount = 0; randomNumberCount < 16; randomNumberCount++)
{
cryptographicallySecureRandomNumberGenerator.GetBytes(randomNumberHolder);
randomNumbers.Add(randomNumberHolder[0]);
}
for (var randomNumberIndex = 0; randomNumberIndex < randomNumbers.Count; randomNumberIndex++)
{
if (remainingLength == 0)
{
break;
}
var randomNumber = randomNumbers[randomNumberIndex];
if (randomNumber < charset.Length)
{
result += charset[randomNumber];
remainingLength--;
}
}
}
return result;
}
private string GenerateSHA256NonceFromRawNonce(string rawNonce)
{
var sha = new SHA256Managed();
var utf8RawNonce = Encoding.UTF8.GetBytes(rawNonce);
var hash = sha.ComputeHash(utf8RawNonce);
var result = string.Empty;
for (var i = 0; i < hash.Length; i++)
{
result += hash[i].ToString("x2");
}
return result;
}
}