You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1360 lines
42 KiB

using Firebase;
using Firebase.Auth;
using IVDataFormat;
using IVServerFormat;
using JetBrains.Annotations;
using System;
using System.Collections;
using System.Reflection;
using UnityEngine;
using UnityEngine.Networking;
public class SingleMgr : Singleton<SingleMgr>
{
#region FCM Data Key Value
/*** 데이터 푸시 START ***/
public const string MDT_ALL = "all";
#if VER_ONESTORE
public const string MDT_OSType = "onestore";
#elif UNITY_ANDROID
public const string MDT_OSType = "android";
#else
public const string MDT_OSType = "ios";
#endif
#if VER_TEST
public const string MDT_Noti = "notitest";
#else
public const string MDT_Noti = "notilive";
#endif
public const string MDK_NotiKey = "show_notibar";
public const string MDK_NotiValue = "Value";
public const string MDK_Key = "Key";
public const string MDK_Value = "Value";
public const string MDK_Msg = "msg";
public const string MDK_ReInitNotice = "reinit_notice";
public const string MDK_ReInitText = "reinit_text";
public const string MDK_ReInitImg = "reinit_img";
public const string MDK_Exit = "exit";
public const string MDK_Kill = "kill";
/*** 데이터 푸시 END ***/
#endregion FCM Data Key Value
public enum eLoginType
{
AuthEmpty = -1,
AUTH_NONE = 0,
AUTH_GUEST = 1,
AUTH_GOOGLE = 2,
AUTH_APPLE = 3,
AUTH_FACEBOOK = 4,
AUTH_TWITTER = 5,
LOGIN_SUCC = 1,
LOGIN_CANCEL = 3,
LOGIN_CANCEL_A = 2,
LOGIN_CANCEL_USER = 0,
LOGIN_FAIL_PRE = -1,
LOGIN_FAIL_A = -2,
LOGIN_FAIL = -3,
LOGIN_FAIL_TOKEN_NULL = -4,
LOGIN_FAIL_TOKEN_ERROR = -5,
LOGIN_FAIL_TASK_NULL = -6,
LOGIN_FAIL_TASK_ERROR = -7,
LOGIN_FAIL_SIGNIN_NULL = -8,
LOGIN_FAIL_SIGNIN_ERROR = -9,
LOGIN_NONE = -99
}
public enum eUserState
{
Logout = 0,
Login = 1,
Refreshing = 8,
Loading = 9
}
public static eUserState UserState { get; private set; }
public static string UserID { get; private set; }
public static string UserToken { get; private set; }
#if !UNITY_EDITOR
private static FirebaseAuth auth = null;
#endif
public static bool IsNeedAttend { get; private set; }
public static bool IsNeedSave { get; private set; }
private static bool B_INIT = false;
private static bool B_INIT_SDK = false;
private static bool B_PLAY = false;
private static bool B_PAUSE = false;
public static bool B_NewDay { get; private set; } = false;
public static bool B_Attending { get; private set; } = false;
private static bool B_DataSaving = false;
private static bool B_CheckTime = false;
public static int I_OfflineTime = 0;
#if VER_DEV
public const int I_Server = 0;
#elif VER_TEST
public const int I_Server = 1;
#elif VER_ZOMBIE
public const int I_Server = 3;
#else
public const int I_Server = 2;
#endif
public static bool B_CCheck = false;
public static bool B_AttendShow = false;
#if APPSFLYER_ANALYTICS
private static bool AppsFlyerTokenSent = false;
private const string AppsFlyerKey = "HMXC9vJHx8vdtvJEvP6HNg";
#if UNITY_ANDROID
private const string AppId = "";
#elif UNITY_IOS
private const string AppId = "1628480211";
private bool tokenSent;
#endif
#endif
#if UNITY_EDITOR
private static string strPushToken = "null";
#else
private static string strPushToken = null;
#endif
private bool bPause = false;
private bool bNotAdsPause = true;
private bool bWaitBagConsume = false;
private bool bWaitPointEnhanceConsume = false;
private bool bWaitTradeConsume = false;
private bool bWaitRaiseConsume = false;
private bool bWaitRouletteConsume = false;
private bool bWaitSetting = false;
private bool bMission = false;
private bool bDailyQuest = false;
private bool bRepeatQuest = false;
private bool bGrowQuest = false;
private bool bWaitFinish = false;
private int iTimeSave = 0;
private int iMinCount = 0;
private int iTouchCount = 0;
private float fTick = 0f;
// 시스템 언어 읽기.
public static SystemLanguage GetSavedLanguage()
{
SystemLanguage ilang = (SystemLanguage)ES3.Load(Global.ES3_Language, -1);
if (ilang < 0)
{
ilang = Application.systemLanguage;
if (ilang != SystemLanguage.Korean &&
ilang != SystemLanguage.Japanese)
{
ilang = SystemLanguage.English;
}
ES3.Save(Global.ES3_Language, (int)ilang);
}
return ilang;
}
public void Init()
{
if (B_INIT) return;
B_INIT = true;
Application.runInBackground = false;
Application.targetFrameRate = 60;
Screen.sleepTimeout = SleepTimeout.NeverSleep;
Input.multiTouchEnabled = false;
UserState = eUserState.Logout;
LocalizationText.SetLanguage(GetSavedLanguage());
#if UNITY_EDITOR
UserID = "editor";
UserToken = PlayerPrefs.GetString("editortoken", "input your token here").Trim();
UserState = eUserState.Login;
#endif
InitializeSDK();
}
private void InitializeSDK()
{
if (B_INIT_SDK) return;
B_INIT_SDK = true;
Logger.Log("Initialize SDK");
#if APPSFLYER_ANALYTICS
#if UNITY_EDITOR || VER_DEV || VER_TEST || VER_ZOMBIE
AppsFlyer.setIsDebug(true);
#else
AppsFlyer.setIsDebug(false);
#endif
AppsFlyer.initSDK(AppsFlyerKey, AppId, this);
AppsFlyer.startSDK();
#if UNITY_IOS
UnityEngine.iOS.NotificationServices.RegisterForNotifications(UnityEngine.iOS.NotificationType.Alert | UnityEngine.iOS.NotificationType.Badge | UnityEngine.iOS.NotificationType.Sound);
#endif
#endif
#if EASY_MOBILE && UNITY_IOS
//Logger.LogWarning("EASY_MOBILE_ATT");
EasyMobile.Privacy.AppTrackingManager.RequestTrackingAuthorization(status => { });
#endif
InitFirebase();
AdsMgr.SInit();
IapMgr.SInit();
}
public void ResetAll()
{
UserID = null;
UserToken = null;
UserState = eUserState.Logout;
B_PAUSE = false;
B_PLAY = false;
B_INIT = false;
B_NewDay = false;
B_Attending = false;
B_CheckTime = false;
B_AttendShow = false;
}
public void FinalizeSDK()
{
if (!B_INIT_SDK)
{
return;
}
B_INIT_SDK = false;
#if APPSFLYER_ANALYTICS
AppsFlyer.stopSDK(true);
#endif
}
public void SetAdsPause(bool badspause)
{
bNotAdsPause = !badspause;
}
public void PauseOff()
{
fTick = 0f;
bPause = false;
if(!SleepModeMgr.GetIsSleep())
SettingMgr.SLoadSettingSound();
}
private void OnApplicationPause(bool pause)
{
if (pause)
{
CancelInvoke("PauseOff");
bPause = true;
SoundMgr.SPauseBgm();
if (!B_PLAY)
return;
GameUIMgr.SPrintTestLog("PAUSE");
NotifyMgr.SSendEndNoti();
TimeUtils.SaveDeviceTime();
}
else
{
SoundMgr.SResumeBgm();
if (!B_PLAY)
return;
GameUIMgr.SPrintTestLog("REPLAY");
B_CheckTime = true;
NotifyMgr.SCancelAllNotification();
TimeUtils.ReCalcNow();
EventMgr.CheckHotTimeOnOff();
B_CheckTime = false;
Invoke(nameof(PauseOff), 0.2f);
}
}
bool isUpdateAlart = false;
public static void ChangeAlartTrue()
{
if (!Instance.isUpdateAlart)
{
Instance.isUpdateAlart = true;
}
}
public static void ChangeAlartFalse()
{
if (Instance.isUpdateAlart)
{
Instance.isUpdateAlart = false;
}
}
private void Update()
{
#if APPSFLYER_ANALYTICS && UNITY_IOS
if (!tokenSent)
{
byte[] token = UnityEngine.iOS.NotificationServices.deviceToken;
if (token != null)
{
AppsFlyeriOS.registerUninstall(token);
tokenSent = true;
}
}
#endif
if (bPause)
return;
fTick += Time.unscaledDeltaTime;
if (fTick >= 1f)
{
int itick = (int)fTick;
if (itick > 1)
{
fTick -= itick;
TimeUtils.AddNowSec(itick);
iMinCount += itick;
iTimeSave += itick;
}
else
{
fTick -= 1f;
TimeUtils.AddNowSec1();
iMinCount++;
iTimeSave++;
}
if (bNotAdsPause && B_PLAY)
{
AdBuffMgr.SUpdateOneSec();
ShopMgr.SUpdateOneSec();
PassMgr.SUpdateOneSec();
BattleMgr.UpdateDpsOneSec();
if (SleepModeMgr.GetIsSleep() == false)
iTouchCount++;
else
iTouchCount = 0;
//if (!SubUIManager.IsNull())
// SubUIManager.Instance.CheckTime();
}
if (iMinCount >= 60)
{
iMinCount = 0;
if (bNotAdsPause && B_PLAY)
{
DataHandler.AddRecord(eCondition.PlayTimeM);
BagMgr.SSetBadge();
PassMgr.SSetBadge(true);
EventMgr.CheckHotTimeOnOff();
}
if (isUpdateAlart)
{
TryUpdateCheck();
}
//접속 도중 이벤트 기간 확인할때 여기 넣으면 될 거 같음(분당 체크)
}
if (bNotAdsPause && B_PLAY && iTimeSave >= 300)
{
CheckSaveData(true);
DataHandler.CheckAllAchivement();
ProfileMgr.SSetBadge();
if (!isUpdateAlart)
{
TryUpdateCheck();
}
}
if (bNotAdsPause && B_PLAY && iTouchCount >= 300 && SleepModeMgr.GetIsSleep() == false && SleepModeMgr.SGetAutoSleep())
{
SleepModeMgr.SOnSleep();
}
}
if (bNotAdsPause && B_PLAY && Input.GetMouseButtonDown(0))
{
iTouchCount = 0;
}
}
// 실시간 업데이트 여부 판별
private void TryUpdateCheck()
{
SvConnectManager.Instance.RequestSvGet(true, 2, UrlApi.GetUrl(UrlApi.GameVer), typeof(dGame), AUpdateCheckSucc, AUpdateCheckFail, false, false);
}
// 통신 실패 - 업데이트 판별.
private void AUpdateCheckFail(SvError error)
{
}
// 통신 성공 - 업데이트 판별.
private void AUpdateCheckSucc(object result)
{
dGame data = result as dGame;
if (data == null)
{
AUpdateCheckFail(new SvError(eErrorCode.NULL_OR_EMPTY));
return;
}
DataHandler.SetUpdateNoticeInfo(data.isNotice, data.updateStartAt, data.updateMsg);
DataHandler.isUpdateNotice();
}
#region Save & Attend
// 날짜 변경 시 처리.
public static void ProcessNewDay()
{
B_NewDay = true;
IsNeedAttend = true;
// 패스 갱신.
if (DataHandler.ResetPass())
PassMgr.SResetPass();
// 상점 갱신.
DataHandler.ResetShop();
ShopMgr.SResetShop();
QuestMgr.SRefreshQuest();
AttendMgr.AttendReckeck();
EventMgr.HotTimeTimerSet();
}
public static void SetPlay(bool bplay)
{
B_PLAY = bplay;
if (bplay)
NotifyMgr.SCancelAllNotification();
}
public static void CheckSaveData(bool bforce)
{
if (bforce)
IsNeedSave = true;
if (IsNeedSave)
{
if (IsNull() || B_DataSaving)
return;
if (SvConnectManager.DataSavingCount > 0)
{
IsNeedSave = true;
return;
}
Instance.SaveDataToServer();
}
}
// 데이터 저장.
private void SaveDataToServer()
{
if (B_DataSaving || SvConnectManager.IsNull())
return;
B_DataSaving = true;
iTimeSave = 0;
DataHandler.OnSaveDataServer();
DataHandler.SaveData();
nSaveData saveData = new nSaveData();
saveData.playCurrency = DataHandler.Goods;
saveData.playUser = DataHandler.PlayData;
saveData.playBox = DataHandler.GetBoxPlayDatas();
saveData.playUserInfo = nUserInfo.GetMyInfo();
saveData.playRecordDaily = DataHandler.GetDailyRecord();
saveData.playRecordTotal = DataHandler.GetTotalRecord();
saveData.playEventRoulette = DataHandler.GetPlayEventRoulette();
saveData.playEventRaise = DataHandler.GetPlayEventRaise();
saveData.playEventTrade = DataHandler.GetPlayEventTrade();
saveData.playRecordDaily = DataHandler.GetDailyRecord();
saveData.playRecordTotal = DataHandler.GetTotalRecord();
SvConnectManager.Instance.RequestSvPost(true, 0, UrlApi.GetUrl(UrlApi.SaveData), typeof(nSaveReturn), ASaveDataSucc, ASaveDataFail, saveData, true);
}
// 통신 실패 - 데이터 저장.
private void ASaveDataFail(SvError error, object request)
{
B_DataSaving = false;
// 가방 소모품 사용 처리 필요.
if (bWaitBagConsume)
{
bWaitBagConsume = false;
BagMgr.SUseConsumeSv();
}
if (bWaitPointEnhanceConsume)
{
bWaitPointEnhanceConsume = false;
EnhanceMgr.SAPointEnhance();
}
if (bWaitTradeConsume)
{
bWaitTradeConsume = false;
//EventMgr.SSVTradeTry();
}
if (bWaitRaiseConsume)
{
bWaitRaiseConsume = false;
}
if (bWaitSetting)
{
bWaitSetting = false;
SettingMgr.SSaveFail();
}
if (bWaitFinish)
{
bWaitFinish = false;
}
if (bMission)
{
bMission = false;
}
if (bDailyQuest)
{
bDailyQuest = false;
}
if (bRepeatQuest)
{
bRepeatQuest = false;
}
if (bGrowQuest)
{
bGrowQuest = false;
}
}
// 통신 성공 - 데이터 저장.
private void ASaveDataSucc(object result, object request)
{
nSaveReturn data = result as nSaveReturn;
if (data == null)
{
ASaveDataFail(new SvError(eErrorCode.NULL_OR_EMPTY), request);
return;
}
DataHandler.SetMailCount(data.mailCount);
B_DataSaving = false;
IsNeedSave = false;
// 가방 소모품 사용 처리 필요.
if (bWaitBagConsume)
{
bWaitBagConsume = false;
BagMgr.SUseConsumeSv();
}
if (bWaitPointEnhanceConsume)
{
bWaitPointEnhanceConsume = false;
EnhanceMgr.SAPointEnhance();
}
if (bWaitTradeConsume)
{
bWaitTradeConsume = false;
EventMgr.SSVTradeTry();
}
if (bWaitRaiseConsume)
{
bWaitRaiseConsume = false;
}
if (bWaitSetting)
{
bWaitSetting = false;
SettingMgr.SSaveSucc();
}
if (bWaitFinish)
{
bWaitFinish = false;
}
if (bMission)
{
bMission = false;
MissionMgr.SClearMission();
}
if (bDailyQuest)
{
bDailyQuest = false;
QuestMgr.SClearDailyQuest(dQuestId);
}
if (bRepeatQuest)
{
bRepeatQuest = false;
QuestMgr.SClearRepeatQuest(rQuestId, rQuestCount);
}
if (bGrowQuest)
{
bGrowQuest = false;
EventMgr.SClearGrowMissionQuest(gQuestId);
}
}
// 가방 소모품 사용 전 데이터 저장.
public static void SaveDataBagConsume()
{
Instance.bWaitBagConsume = true;
Instance.SaveDataToServer();
}
//포인트 사용 전 저장하기
public static void SaveDataPointEnhanceConsume()
{
Instance.bWaitPointEnhanceConsume = true;
Instance.SaveDataToServer();
}
//이벤트 교환 재화 사용 전 저장하기
public static void SaveDataEventTradeConsume()
{
Instance.bWaitTradeConsume = true;
Instance.SaveDataToServer();
}
//이벤트 키우기 재화 사용 전 저장하기
public static void SaveDataEventRaiseConsume()
{
Instance.bWaitRaiseConsume = true;
Instance.SaveDataToServer();
}
public static void SaveDataEventRouletteConsume()
{
Instance.bWaitRouletteConsume = true;
Instance.SaveDataToServer();
}
// 가방 소모품 사용 전 데이터 저장.
public static void SaveDataSetting()
{
Instance.bWaitSetting = true;
Instance.SaveDataToServer();
}
//미션 클리어 전 데이터 저장
public static void SaveDataMission()
{
Instance.bMission = true;
Instance.SaveDataToServer();
}
int dQuestId = 0;
//일일미션 클리어 전 데이터 저장
public static void SaveDataDQuest(int id)
{
Instance.bDailyQuest = true;
Instance.dQuestId = id;
Instance.SaveDataToServer();
}
int rQuestId = 0;
int rQuestCount = 0;
//반복미션 클리어 전 데이터 저장
public static void SaveDataRQuest(int id, int cnt)
{
Instance.bRepeatQuest = true;
Instance.rQuestId = id;
Instance.rQuestCount = cnt;
Instance.SaveDataToServer();
}
int gQuestId = 0;
//성장미션 클리어 전 데이터 저장
public static void SaveDataGQuest(int id)
{
Instance.bGrowQuest = true;
Instance.gQuestId = id;
Instance.SaveDataToServer();
}
#endregion Save & Attend
#region MoveContent
public static void MoveContent(eEventMoveType content)
{
switch (content)
{
case eEventMoveType.EnhnaceGold:
case eEventMoveType.EnhancePoint:
case eEventMoveType.EnhanceAwakne:
EnhanceMgr.SMoveEnhance(content);
break;
case eEventMoveType.SummonWeapon:
case eEventMoveType.SummonArmor:
case eEventMoveType.SummonAcc:
case eEventMoveType.SummonTreasure:
GachaMgr.SMoveGacha(content);
break;
case eEventMoveType.BagWeapon:
case eEventMoveType.BagArmorCape:
case eEventMoveType.BagArmorHat:
case eEventMoveType.BagArmorShoes:
case eEventMoveType.BagAccEar:
case eEventMoveType.BagAccNeck:
case eEventMoveType.BagAccRing:
case eEventMoveType.BagConsume:
BagMgr.SMoveBag(content);
break;
case eEventMoveType.BagTreasure:
case eEventMoveType.BagTreasureR:
TreasureMgr.SopenTreasure();
break;
case eEventMoveType.skillActive:
case eEventMoveType.skillPassive:
SkillMgr.SMoveSkill(content);
break;
case eEventMoveType.pet:
case eEventMoveType.petSprit:
PetMgr.SMovePet(content);
break;
case eEventMoveType.DgGold:
case eEventMoveType.DgStone:
case eEventMoveType.DgPet:
case eEventMoveType.DgAwaken:
DungeonMgr.SMoveDungeon(content);
break;
case eEventMoveType.ProfileIcon:
case eEventMoveType.ProfileTitleBattle:
case eEventMoveType.ProfileTitleEquip:
case eEventMoveType.ProfileTitleSummon:
case eEventMoveType.ProfileTitleDungeon:
case eEventMoveType.ProfileTitleEtc:
ProfileMgr.SMoveProfile(content);
break;
case eEventMoveType.AdBuff:
AdBuffMgr.SMoveAdbuff();
break;
case eEventMoveType.Attend:
AttendMgr.SMoveAttend(content);
break;
case eEventMoveType.SettingSys:
case eEventMoveType.SettingId:
SettingMgr.SMoveSetting(content);
break;
default:
return;
}
}
#endregion
#region Account
public void LoginRefresh()
{
}
public void LogoutAuto()
{
}
#endregion Account
#region Firebase
private void InitFirebase()
{
#if UNITY_EDITOR
Invoke(nameof(OnInitFirebaseSucc), 1f);
#else
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
var dependencyStatus = task.Result;
if (dependencyStatus == DependencyStatus.Available)
{
FirebaseApp app = FirebaseApp.DefaultInstance;
Invoke(nameof(OnInitFirebaseSucc), 1f);
}
else
{
Debug.LogError(FormatString.StringFormat("Could not resolve all Firebase dependencies: {0}", dependencyStatus));
Invoke(nameof(OnInitFirebaseFail), 1f);
}
});
#endif
}
public void OnInitFirebaseSucc()
{
#if FIREBASE_PUSH
Messaging.FirebaseMessaging.TokenReceived += OnTokenReceived;
Messaging.FirebaseMessaging.MessageReceived += OnMessageReceived;
#if UNITY_ANDROID
#elif UNITY_IOS
Messaging.FirebaseMessaging.RequestPermissionAsync();
#endif
#endif
#if FIREBASE_CRASHLYTICS
CrashlyticsInit.Init();
#endif
CheckLoginUser();
}
public void OnInitFirebaseFail()
{
OpenPopup1Button(LocalizationText.GetText("exc_vergoogleplay"), GameFinishOnly);
}
#endregion Firebase
#region Firebase Delegate
#if FIREBASE_PUSH
// 토큰 획득.
public void OnTokenReceived(object sender, Messaging.TokenReceivedEventArgs token)
{
strPushToken = token.Token;
bFCMInit = true;
//int itopicall = 0;
//int itopicnoti = -1;
//int itopiclang = -1;
//try
//{
// itopicall = ObscuredPrefs.GetInt(Global.PREFS_TopicAll, 0);
// itopicnoti = ObscuredPrefs.GetInt(Global.PREFS_TopicNoti, -1);
// itopiclang = ObscuredPrefs.GetInt(Global.PREFS_TopicLang, -1);
//}
//catch { }
//if (itopicall == 0)
//{
// Messaging.FirebaseMessaging.SubscribeAsync(Global.MDT_ALL);
// ObscuredPrefs.SetInt(Global.PREFS_TopicAll, 1);
// ObscuredPrefs.Save();
//}
//if (itopicnoti == -1)
//{
// if (Global.MDT_Noti.Equals("notitest"))
// {
// Messaging.FirebaseMessaging.SubscribeAsync(Global.MDT_Noti);
// ObscuredPrefs.SetInt(Global.PREFS_TopicNoti, 1);
// ObscuredPrefs.Save();
// }
// else if (Global.MDT_Noti.Equals("notilive"))
// {
// Messaging.FirebaseMessaging.SubscribeAsync(Global.MDT_Noti);
// ObscuredPrefs.SetInt(Global.PREFS_TopicNoti, 2);
// ObscuredPrefs.Save();
// }
//}
//else
//{
// if (Global.MDT_Noti.Equals("notilive"))
// {
// if (itopicnoti == 1)
// {
// Messaging.FirebaseMessaging.UnsubscribeAsync("notitest");
// Messaging.FirebaseMessaging.SubscribeAsync(Global.MDT_Noti);
// ObscuredPrefs.SetInt(Global.PREFS_TopicNoti, 2);
// ObscuredPrefs.Save();
// }
// }
// else if (Global.MDT_Noti.Equals("notitest"))
// {
// if (itopicnoti == 2)
// {
// Messaging.FirebaseMessaging.UnsubscribeAsync("notilive");
// Messaging.FirebaseMessaging.SubscribeAsync(Global.MDT_Noti);
// ObscuredPrefs.SetInt(Global.PREFS_TopicNoti, 1);
// ObscuredPrefs.Save();
// }
// }
//}
//if (itopicnoti == 0)
//{
// Messaging.FirebaseMessaging.SubscribeAsync(Global.MDT_Noti);
// ObscuredPrefs.SetInt(Global.PREFS_TopicNoti, 1);
// ObscuredPrefs.Save();
//}
//string strostype = ObscuredPrefs.GetString(Global.PREFS_TopicOSType, null);
//if (!Global.MDT_OSType.Equals(strostype))
//{
// if (!string.IsNullOrEmpty(strostype))
// Messaging.FirebaseMessaging.UnsubscribeAsync(strostype);
// Messaging.FirebaseMessaging.SubscribeAsync(Global.MDT_OSType);
// ObscuredPrefs.SetString(Global.PREFS_TopicOSType, Global.MDT_OSType);
// ObscuredPrefs.Save();
//}
//if (Global.iLanguage != itopiclang)
//{
// if (itopiclang >= 0 && itopiclang < Global.arStrLangTopic.Length)
// Messaging.FirebaseMessaging.UnsubscribeAsync(Global.arStrLangTopic[itopiclang]);
// if (Global.iLanguage >= 0 && Global.iLanguage < Global.arStrLangTopic.Length)
// {
// Messaging.FirebaseMessaging.SubscribeAsync(Global.arStrLangTopic[Global.iLanguage]);
// ObscuredPrefs.SetInt(Global.PREFS_TopicLang, Global.iLanguage);
// ObscuredPrefs.Save();
// }
//}
#if APPSFLYER_ANALYTICS && UNITY_ANDROID
AppsFlyerAndroid.updateServerUninstallToken(token.Token);
#endif
}
// 푸시 수신.
public void OnMessageReceived(object sender, Messaging.MessageReceivedEventArgs e)
{
if (e.Message.Data != null && e.Message.Data.Count > 0)
{
string key = null;
string value = null;
foreach (KeyValuePair<string, string> item in e.Message.Data)
{
if (item.Key.Equals(MDK_Key))
key = item.Value;
else if (item.Key.Equals(MDK_Value))
value = item.Value;
else if (item.Key.Equals(MDK_NotiKey))
key = item.Value;
}
Logger.Log("OnMessageReceived: Data " + key + " : " + value);
//if (!string.IsNullOrEmpty(key))
// DataMgr.CheckMessageDataS(key, value);
}
}
#endif
#endregion Firebase Delegate
#region Firebase Login
// 로그인 된 유저 체크.
private static void CheckLoginUser()
{
#if UNITY_EDITOR
MainMgr.SSetLoginUi(0);
#else
int ilogintype = ES3.Load(Global.ES3_Login, 0);
auth = FirebaseAuth.DefaultInstance;
//auth.StateChanged += AuthStateChanged;
//AuthStateChanged(this, null);
// 이전에 로그인 한 유저 정보가 없음.
if (ilogintype <= 0 || auth == null || auth.CurrentUser == null)
{
ES3.Save(Global.ES3_Login, 0);
MainMgr.SSetLoginUi(0);
return;
}
FirebaseUser user = auth.CurrentUser;
if (user == null || string.IsNullOrEmpty(user.UserId))
{
ES3.Save(Global.ES3_Login, 0);
MainMgr.SSetLoginUi(0);
return;
}
// 이전에 로그인 한 유저 정보가 있음.
user.TokenAsync(true).ContinueWith(tasktoken =>
{
if (tasktoken.IsCompleted && !tasktoken.IsCanceled && !tasktoken.IsFaulted)
{
//Logger.Log(string.Format("FIREBASE TOKEN: {0}", tasktoken.Result));
if (string.IsNullOrEmpty(user.UserId))
{
Logger.Log("UserId is empty.");
ES3.Save(Global.ES3_Login, 0);
MainMgr.SSetLoginUi(0);
}
else
{
UserID = user.UserId;
UserToken = tasktoken.Result;
UserState = eUserState.Login;
MainMgr.SSetLoginUi(0);//수정해봄
FormatString.PrintLog("CheckLoginUser");
FormatString.PrintLog(UserToken);
}
}
else if (tasktoken.IsCanceled)
{
Logger.Log("TokenAsync was canceled.");
ES3.Save(Global.ES3_Login, 0);
MainMgr.SSetLoginUi(0);
}
else if (tasktoken.IsFaulted)
{
Logger.Log("TokenAsync encountered an error: " + tasktoken.Exception);
OpenPopup1Button(tasktoken.Exception.Message);
ES3.Save(Global.ES3_Login, 0);
MainMgr.SSetLoginUi(0);
}
});
#endif
}
public static void AuthResult(eLoginType logintype, eLoginType loginres, string strresult, string strid)
{
Logger.Log("SingleMgr - AuthResult " + logintype.ToString() + " / " + loginres.ToString());
switch (loginres)
{
// succ
case eLoginType.LOGIN_SUCC:
UserID = strid;
UserToken = strresult;
UserState = eUserState.Login;
ES3.Save(Global.ES3_Login, (int)logintype);
Debug.LogWarningFormat("Login Success with UID : {0}, USER_TOKEN : {1}", UserID, UserToken);
MainMgr.SPlatformLoginSucc();
return;
// cancel
case eLoginType.LOGIN_CANCEL:
OpenPopup1Button(LocalizationText.GetText("error_login_cancel"));
Logger.LogWarning("LOGIN_CANCEL");
break;
// cancel another
case eLoginType.LOGIN_CANCEL_A:
OpenPopup1Button(LocalizationText.GetText("error_login_cancel_a"));
Logger.LogWarning("LOGIN_CANCEL_A");
break;
// cancel user
case eLoginType.LOGIN_CANCEL_USER:
Logger.LogWarning("LOGIN_CANCEL_USER");
break;
// fail pre
case eLoginType.LOGIN_FAIL_PRE:
OpenPopup1Button(FormatString.StringFormat(LocalizationText.GetText("error_login_fail_pre"), strresult));
Logger.Log(string.Format("LOGIN_FAIL_PRE: {0} ::: {1}", strresult, strid));
break;
// fail another
case eLoginType.LOGIN_FAIL_A:
OpenPopup1Button(FormatString.StringFormat(LocalizationText.GetText("error_login_fail_a"), strresult));
Logger.Log(string.Format("LOGIN_FAIL_A: {0} ::: {1}", strresult, strid));
break;
// fail
case eLoginType.LOGIN_FAIL:
OpenPopup1Button(FormatString.StringFormat(LocalizationText.GetText("error_login_fail"), strresult));
Logger.Log(string.Format("LOGIN_FAIL: {0} ::: {1}", strresult, strid));
break;
// fail token null
case eLoginType.LOGIN_FAIL_TOKEN_NULL:
OpenPopup1Button(LocalizationText.GetText("error_login_token_null"));
Logger.LogWarning("LOGIN_FAIL_TOKEN_NULL");
break;
// fail token error
case eLoginType.LOGIN_FAIL_TOKEN_ERROR:
OpenPopup1Button(FormatString.StringFormat(LocalizationText.GetText("error_login_token_error"), strresult));
Logger.Log(string.Format("LOGIN_FAIL_TOKEN_ERROR: {0} ::: {1}", strresult, strid));
break;
// fail task null
case eLoginType.LOGIN_FAIL_TASK_NULL:
OpenPopup1Button(LocalizationText.GetText("error_login_task_null"));
Logger.LogWarning("LOGIN_FAIL_TASK_NULL");
break;
// fail task error
case eLoginType.LOGIN_FAIL_TASK_ERROR:
OpenPopup1Button(FormatString.StringFormat(LocalizationText.GetText("error_login_task_error"), strresult));
Logger.Log(string.Format("LOGIN_FAIL_TASK_ERROR: {0} ::: {1}", strresult, strid));
break;
// fail task null
case eLoginType.LOGIN_FAIL_SIGNIN_NULL:
OpenPopup1Button(LocalizationText.GetText("error_login_signin_null"));
Logger.LogWarning("LOGIN_FAIL_SIGNIN_NULL");
break;
// fail task error
case eLoginType.LOGIN_FAIL_SIGNIN_ERROR:
OpenPopup1Button(FormatString.StringFormat(LocalizationText.GetText("error_login_signin_error"), strresult));
Logger.Log(string.Format("LOGIN_FAIL_SIGNIN_ERROR: {0} ::: {1}", strresult, strid));
break;
// fail another
default:
OpenPopup1Button(FormatString.StringFormat(LocalizationText.GetText("error_login_default"), strresult));
Logger.Log(string.Format("LOGIN_FAIL_DEFAULT: {0} ::: {1}", strresult, strid));
break;
}
MainMgr.SLoginFail();
}
// 게스트 로그인.
public static void AuthAnonymous()
{
#if UNITY_EDITOR
AuthResult(eLoginType.AUTH_GUEST, eLoginType.LOGIN_SUCC, PlayerPrefs.GetString("editortoken", "input your token here").Trim(), "editor");
#else
auth = FirebaseAuth.DefaultInstance;
Logger.Log("AuthAnonymous - SignInAnonymouslyAsync");
auth.SignInAnonymouslyAsync().ContinueWith(task =>
{
Logger.Log("AuthAnonymous - CheckTask");
if (task != null && task.IsCompleted && !task.IsCanceled && !task.IsFaulted && task.Result != null)
{
Logger.Log("AuthAnonymous - RequestToken");
FirebaseUser user = task.Result.User;
user.TokenAsync(true).ContinueWith(tasktoken =>
{
Logger.Log("AuthAnonymous - CheckToken");
if (tasktoken != null && tasktoken.IsCompleted && !tasktoken.IsCanceled && !tasktoken.IsFaulted && tasktoken.Result != null)
{
Logger.Log("AuthAnonymous - Complete");
AuthResult(eLoginType.AUTH_GUEST, eLoginType.LOGIN_SUCC, tasktoken.Result, user.UserId);
}
else
{
Logger.Log("AuthAnonymous - TokenError");
if (tasktoken == null)
{
AuthResult(eLoginType.AUTH_GUEST, eLoginType.LOGIN_FAIL_TOKEN_NULL, null, null);
}
else if (tasktoken.IsCanceled)
{
AuthResult(eLoginType.AUTH_GUEST, eLoginType.LOGIN_CANCEL, null, null);
}
else if (tasktoken.IsFaulted)
{
AuthResult(eLoginType.AUTH_GUEST, eLoginType.LOGIN_FAIL, tasktoken.Exception.Message, tasktoken.Exception.ToString());
}
else
{
AuthResult(eLoginType.AUTH_GUEST, eLoginType.LOGIN_FAIL_TOKEN_ERROR, tasktoken.Exception.Message, tasktoken.Exception.ToString());
}
}
});
}
else
{
Logger.Log("AuthAnonymous - TaskError");
if (task == null)
{
AuthResult(eLoginType.AUTH_GUEST, eLoginType.LOGIN_FAIL_TASK_NULL, null, null);
}
else if (task.IsCanceled)
{
AuthResult(eLoginType.AUTH_GUEST, eLoginType.LOGIN_CANCEL_A, null, null);
}
else if (task.IsFaulted)
{
AuthResult(eLoginType.AUTH_GUEST, eLoginType.LOGIN_FAIL_A, task.Exception.Message, task.Exception.ToString());
}
else
{
AuthResult(eLoginType.AUTH_GUEST, eLoginType.LOGIN_FAIL_TASK_ERROR, task.Exception.Message, task.Exception.ToString());
}
}
});
#endif
}
#endregion Firebase Login
#region AppsFlyer Delegate
#if APPSFLYER_ANALYTICS
// 전환 데이터를 가져올때 사용.
public void onConversionDataSuccess(string conversionData)
{
#if UNITY_EDITOR || VER_DEV || VER_TEST || VER_ZOMBIE
Logger.Log(" *************************** onConversionDataSuccess : " + conversionData);
#endif
AppsFlyer.AFLog("onConversionDataSuccess", conversionData);
Dictionary<string, object> conversionDataDictionary = AppsFlyer.CallbackStringToDictionary(conversionData);
// add deferred deeplink logic here
}
// 전환 데이터를 가져오지 못했을 경우.
public void onConversionDataFail(string error)
{
#if UNITY_EDITOR || VER_DEV || VER_TEST || VER_ZOMBIE
Logger.LogWarning(" *************************** onConversionDataFail : " + error);
#endif
AppsFlyer.AFLog("onConversionDataFail", error);
}
// 딥링크를 통해 열릴 때 딥링크 데이터를 가져옴.
public void onAppOpenAttribution(string attributionData)
{
#if UNITY_EDITOR || VER_DEV || VER_TEST || VER_ZOMBIE
Logger.Log(" *************************** onAppOpenAttribution : " + attributionData);
#endif
AppsFlyer.AFLog("onAppOpenAttribution", attributionData);
Dictionary<string, object> attributionDataDictionary = AppsFlyer.CallbackStringToDictionary(attributionData);
// add direct deeplink logic here
}
// 딥링크 데이터를 가져오는동안 오류.
public void onAppOpenAttributionFailure(string error)
{
#if UNITY_EDITOR || VER_DEV || VER_TEST || VER_ZOMBIE
Logger.LogWarning(" *************************** onAppOpenAttributionFailure : " + error);
#endif
AppsFlyer.AFLog("onAppOpenAttributionFailure", error);
}
#endif
#endregion AppsFlyer Delegate
#region Popup
public static void OpenPopupCheckNet(string strmsg, System.Action actionyes = null, string strtitle = null, string stryes = null, bool bclose = true, float ftime = 0f)
{
if (B_PLAY)
{
GameUIMgr.SOpenPopupCheckNet(strmsg, actionyes, strtitle, stryes, bclose, ftime);
}
else if (MainMgr.IsMain())
{
MainMgr.SOpenPopupCheckNet(strmsg, actionyes, strtitle, stryes, bclose, ftime);
}
}
public static void OpenPopup1Button(string strmsg, System.Action actionyes = null, string strtitle = null, string stryes = null, bool bclose = true, float ftime = 0f)
{
if (B_PLAY)
{
GameUIMgr.SOpenPopup1Button(strmsg, actionyes, strtitle, stryes, bclose, ftime);
}
else if (MainMgr.IsMain())
{
MainMgr.SOpenPopup1Button(strmsg, actionyes, strtitle, stryes, bclose, ftime);
}
}
public static void OpenPopup2Button(string strmsg, System.Action actionyes = null, System.Action actionno = null, string strtitle = null, string stryes = null, string strno = null)
{
if (B_PLAY)
{
GameUIMgr.SOpenPopup2Button(strmsg, actionyes, actionno, strtitle, stryes, strno);
}
else if (MainMgr.IsMain())
{
MainMgr.SOpenPopup2Button(strmsg, actionyes, actionno, strtitle, stryes, strno);
}
}
public static void OpenToast(string strmsg, float ftime = 2f, int itype = 1)
{
if (B_PLAY)
{
GameUIMgr.SOpenToast(strmsg, ftime, itype);
}
else if (MainMgr.IsMain())
{
MainMgr.SOpenToast(strmsg, ftime);
}
}
#endregion Popup
#region Finish & Update
public static void GameFinishDate()
{
CoverCamera.Hold();
BattleMgr.Instance.BattlePause = true;
DataHandler.PlayData.SaveDate(TimeUtils.Now().AddDays(-1d));
#if UNITY_EDITOR
UnityEditor.EditorApplication.ExecuteMenuItem("Edit/Play");
#else
Application.Quit();
#endif
}
public static void GameFinishOnly()
{
CoverCamera.Hold();
#if UNITY_EDITOR
UnityEditor.EditorApplication.ExecuteMenuItem("Edit/Play");
#else
Application.Quit();
#endif
}
public static void GameFinish()
{
CoverCamera.Hold();
if (B_PLAY)
Instance.StartCoroutine(nameof(GameFinishProcess));
}
private IEnumerator GameFinishProcess()
{
if (B_PLAY)
{
NotifyMgr.SSendEndNoti();
}
yield return null;
yield return null;
yield return null;
DataHandler.SaveData();
yield return null;
yield return null;
yield return null;
#if UNITY_EDITOR
UnityEditor.EditorApplication.ExecuteMenuItem("Edit/Play");
yield break;
#else
Application.Quit();
#endif
}
public static void GameFinishSvSave()
{
CoverCamera.Hold();
if (B_PLAY)
Instance.StartCoroutine(nameof(GameFinishSvSaveProcess));
}
private IEnumerator GameFinishSvSaveProcess()
{
GameUIMgr.SOpenToast(LocalizationText.GetText("msg_exitsave"), 99f, 1);
if (B_PLAY)
{
NotifyMgr.SSendEndNoti();
}
yield return null;
yield return null;
yield return null;
DataHandler.SaveData();
yield return null;
yield return null;
yield return null;
bWaitFinish = true;
Instance.SaveDataToServer();
while (bWaitFinish)
{
yield return YieldInstructionCache.WaitForSeconds(0.5f);
}
#if UNITY_EDITOR
UnityEditor.EditorApplication.ExecuteMenuItem("Edit/Play");
yield break;
#else
Application.Quit();
#endif
}
public static void GameUpdate()
{
CoverCamera.Hold();
#if VER_ONESTORE
Application.OpenURL(LocalizationText.GetText("update_onestore"));
#elif UNITY_IOS
Application.OpenURL(LocalizationText.GetText("update_apple"));
#else
Application.OpenURL(LocalizationText.GetText("update_google"));
#endif
}
#endregion Finish & Update
#region Others
public static void ResetCount()
{
Instance.iTouchCount = 0;
}
#endregion
}