Project_WL/Assets/Script/Info/TitleInfo.cs

385 lines
13 KiB
C#

using AppleAuth;
using AppleAuth.Enums;
using AppleAuth.Extensions;
using AppleAuth.Interfaces;
using AppleAuth.Native;
using CodeStage.AntiCheat.Storage;
//using Facebook.Unity;
//using Firebase.Auth;
//using Google;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
using Random = UnityEngine.Random;
using TMPro;
#if UNITY_ANDROID
using UnityEngine.Android;
#endif
public class TitleInfo : MyCoroutine
{
public TextMeshProUGUI label_version, label_msg;
public TextAsset ta_versioncode;
public GameObject[] gos_LoginButton; // 애플(0) 구글(1) 게스트(2)
public TMP_InputField Input_ID;
private IAppleAuthManager appleAuthManager;
bool activeButtons, GoLogin;
int LoginFail = 0;
private void Awake()
{
Input_ID.gameObject.SetActive(false);
InActive_LoginButton();
}
IEnumerator Start()
{
label_version.text = DSUtil.Format("{0}({1})", Application.version, ServerInfo.Ins.VersionCode);
label_msg.text = "";
while (!TableChecker.Ins.CheckAllLoad()) yield return null; // 테이블 로딩 기다리기
//#if FGB_LIVE
// SRDebug.Instance.IsTriggerEnabled = false;
//#else
// SRDebug.Instance.IsTriggerEnabled = true;
//#endif
label_msg.text = table_localtext.Ins.Get_Text(118);
ServerInfo.Ins.VersionCode = int.Parse(ta_versioncode.text);
#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, 119,
() => { 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(120);
yield return new WaitForSeconds(0.1f);
Login();
}
void Update()
{
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;
}
}
void Active_LoginButton()
{
label_msg.text = table_localtext.Ins.Get_Text(121);
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
Input_ID.gameObject.SetActive(true);
Input_ID.text = PlayerPrefs.GetString(MyValue.OptionKey_UserID, "TestID");
#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.Login(ServerComplete);
}
#endif
}
public void OnClick_DevLogin()
{
label_msg.text = table_localtext.Ins.Get_Text(122);
Input_ID.gameObject.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)
{
label_msg.text = table_localtext.Ins.Get_Text(124);
label_msg.gameObject.AddComponent<TextAlphaPingPong>();
AllComplete = true;
#if UNITY_EDITOR
if (ServerInfo.Ins.IsLiveServer())
Popup.Ins.Set(ePopupType.Two, -1, OnClick_Screen, DSUtil.Quit);
#endif
}
bool AllComplete = false;
public void OnClick_Screen()
{
if (AllComplete)
{
label_msg.text = table_localtext.Ins.Get_Text(125);
SceneManager.LoadScene("Ingame");
}
}
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;
}
}