310 lines
11 KiB
C#
310 lines
11 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Threading.Tasks;
|
|
using UnityEngine;
|
|
using Firebase.Extensions;
|
|
namespace Kill.Base
|
|
{
|
|
public class FireBaseCtrl : MonoBehaviour
|
|
{
|
|
Firebase.Auth.FirebaseAuth auth;
|
|
Firebase.Auth.FirebaseUser user;
|
|
Firebase.FirebaseApp app;
|
|
public static FireBaseCtrl Instance;
|
|
Action<bool, string> loginStatusCallBack;
|
|
|
|
// 登录状态属性
|
|
public bool IsLoggedIn { get; private set; } = false;
|
|
public string CurrentUserId { get; private set; } = "";
|
|
|
|
// 添加网络状态和初始化状态
|
|
public bool IsInitialized { get; private set; } = false;
|
|
public bool IsNetworkAvailable { get; private set; } = true; // 默认假设网络可用
|
|
|
|
// 添加登录状态枚举
|
|
public enum LoginState
|
|
{
|
|
Unknown, // 未知状态
|
|
NotLoggedIn, // 用户未登录
|
|
LoggedIn, // 用户已登录
|
|
Initializing, // 正在初始化
|
|
NetworkError, // 网络错误
|
|
AuthPending // 认证正在进行中
|
|
}
|
|
|
|
public LoginState CurrentLoginState { get; private set; } = LoginState.Unknown;
|
|
|
|
void Awake()
|
|
{
|
|
Instance = this;
|
|
DontDestroyOnLoad(gameObject);
|
|
}
|
|
|
|
public async Task Init()
|
|
{
|
|
|
|
await Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
|
|
{
|
|
var dependencyStatus = task.Result;
|
|
if (dependencyStatus == Firebase.DependencyStatus.Available)
|
|
{
|
|
// Create and hold a reference to your FirebaseApp,
|
|
// where app is a Firebase.FirebaseApp property of your application class.
|
|
app = Firebase.FirebaseApp.DefaultInstance;
|
|
|
|
// Set a flag here to indicate whether Firebase is ready to use by your app.
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError(string.Format(
|
|
"===Could not resolve all Firebase dependencies: {0}", dependencyStatus));
|
|
// Firebase Unity SDK is not safe to use here.
|
|
}
|
|
});
|
|
CurrentLoginState = LoginState.Initializing;
|
|
|
|
try
|
|
{
|
|
// 检查Firebase依赖
|
|
var dependencyStatus = await Firebase.FirebaseApp.CheckAndFixDependenciesAsync();
|
|
|
|
if (dependencyStatus == Firebase.DependencyStatus.Available)
|
|
{
|
|
auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
|
|
auth.StateChanged += AuthStateChanged;
|
|
AuthStateChanged(this, null);
|
|
IsInitialized = true;
|
|
Debug.Log("===FirebaseCtrl Init");
|
|
|
|
// 检查初始状态
|
|
CheckInitialState();
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError($"===Firebase依赖不可用: {dependencyStatus}");
|
|
CurrentLoginState = LoginState.NetworkError;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.LogError($"===Firebase初始化失败: {ex.Message}");
|
|
CurrentLoginState = LoginState.NetworkError;
|
|
}
|
|
Firebase.Messaging.FirebaseMessaging.TokenReceived+= OnTokenReceived;
|
|
|
|
Firebase.Messaging.FirebaseMessaging.MessageReceived+= OnMessageReceived;
|
|
|
|
|
|
}
|
|
|
|
void CheckInitialState()
|
|
{
|
|
// 检查是否有当前用户
|
|
if (auth.CurrentUser != null)
|
|
{
|
|
CurrentLoginState = LoginState.LoggedIn;
|
|
IsLoggedIn = true;
|
|
CurrentUserId = auth.CurrentUser.UserId;
|
|
}
|
|
else
|
|
{
|
|
CurrentLoginState = LoginState.NotLoggedIn;
|
|
IsLoggedIn = false;
|
|
CurrentUserId = "";
|
|
}
|
|
}
|
|
|
|
public void SetLoginStatusCallBack(Action<bool, string> callBack)
|
|
{
|
|
loginStatusCallBack = callBack;
|
|
if (user != null)
|
|
loginStatusCallBack?.Invoke(true, user.UserId);
|
|
}
|
|
|
|
void AuthStateChanged(object sender, System.EventArgs eventArgs)
|
|
{
|
|
if (auth.CurrentUser != user)
|
|
{
|
|
bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null;
|
|
if (!signedIn && user != null)
|
|
{
|
|
Debug.Log("===用户登出 " + user.UserId);
|
|
IsLoggedIn = false;
|
|
CurrentUserId = "";
|
|
CurrentLoginState = LoginState.NotLoggedIn;
|
|
loginStatusCallBack?.Invoke(false, user.UserId);
|
|
}
|
|
user = auth.CurrentUser;
|
|
if (signedIn)
|
|
{
|
|
Debug.Log("===用户登录 " + user.UserId);
|
|
IsLoggedIn = true;
|
|
CurrentUserId = user.UserId;
|
|
CurrentLoginState = LoginState.LoggedIn;
|
|
loginStatusCallBack?.Invoke(true, user.UserId);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 同步检查当前登录状态的方法
|
|
public bool CheckLoginStatus()
|
|
{
|
|
return auth != null && auth.CurrentUser != null;
|
|
}
|
|
|
|
// 更详细的登录状态检查方法
|
|
public LoginStateDetail GetDetailedLoginStatus()
|
|
{
|
|
var detail = new LoginStateDetail();
|
|
|
|
// 检查Firebase是否已初始化
|
|
if (!IsInitialized)
|
|
{
|
|
detail.State = LoginState.Initializing;
|
|
detail.Description = "Firebase正在初始化";
|
|
return detail;
|
|
}
|
|
|
|
// 检查网络状态
|
|
if (!IsNetworkAvailable)
|
|
{
|
|
detail.State = LoginState.NetworkError;
|
|
detail.Description = "网络不可用,请检查网络连接";
|
|
return detail;
|
|
}
|
|
|
|
// 检查认证状态
|
|
if (auth != null)
|
|
{
|
|
if (auth.CurrentUser != null)
|
|
{
|
|
detail.State = LoginState.LoggedIn;
|
|
detail.Description = "用户已登录";
|
|
detail.UserId = auth.CurrentUser.UserId;
|
|
detail.DisplayName = auth.CurrentUser.DisplayName;
|
|
}
|
|
else
|
|
{
|
|
detail.State = LoginState.NotLoggedIn;
|
|
detail.Description = "用户未登录";
|
|
}
|
|
}
|
|
else
|
|
{
|
|
detail.State = LoginState.Unknown;
|
|
detail.Description = "认证服务未准备好";
|
|
}
|
|
|
|
return detail;
|
|
}
|
|
|
|
public void CreatUserByEmail(string email, string password, Action<bool, string> callBack)
|
|
{
|
|
if (!IsInitialized)
|
|
{
|
|
callBack(false, "服务未初始化完成,请稍后重试");
|
|
return;
|
|
}
|
|
|
|
CurrentLoginState = LoginState.AuthPending;
|
|
|
|
auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
|
|
{
|
|
if (task.IsCanceled)
|
|
{
|
|
Debug.Log("===取消创建用户");
|
|
CurrentLoginState = LoginState.NotLoggedIn;
|
|
callBack(false, "取消创建用户");
|
|
return;
|
|
}
|
|
if (task.IsFaulted)
|
|
{
|
|
Debug.Log("===创建用户失败 " + task.Exception);
|
|
callBack(false, GetFriendlyErrorMessage(task.Exception));
|
|
return;
|
|
}
|
|
|
|
Firebase.Auth.AuthResult result = task.Result;
|
|
CurrentLoginState = LoginState.LoggedIn;
|
|
callBack(true, "");
|
|
Debug.LogFormat("===创建用户成功: {0} ({1})",
|
|
result.User.DisplayName, result.User.UserId);
|
|
});
|
|
}
|
|
|
|
public void LoginWithEmail(string email, string password, Action<bool, string> callBack)
|
|
{
|
|
if (!IsInitialized)
|
|
{
|
|
callBack(false, "服务未初始化完成,请稍后重试");
|
|
return;
|
|
}
|
|
|
|
CurrentLoginState = LoginState.AuthPending;
|
|
|
|
auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
|
|
{
|
|
if (task.IsCanceled)
|
|
{
|
|
Debug.Log("===登录取消");
|
|
CurrentLoginState = LoginState.NotLoggedIn;
|
|
callBack(false, "登录取消");
|
|
return;
|
|
}
|
|
if (task.IsFaulted)
|
|
{
|
|
string errorMessage = GetFriendlyErrorMessage(task.Exception);
|
|
Debug.Log("===登录出错" + task.Exception);
|
|
callBack(false, errorMessage);
|
|
return;
|
|
}
|
|
|
|
Firebase.Auth.AuthResult result = task.Result;
|
|
CurrentLoginState = LoginState.LoggedIn;
|
|
callBack(true, result.User.UserId);
|
|
Debug.LogFormat("登录成功: {0} ({1})",
|
|
string.IsNullOrEmpty(result.User.DisplayName) ? "" : result.User.DisplayName,
|
|
result.User.UserId);
|
|
});
|
|
}
|
|
|
|
public void Logout()
|
|
{
|
|
auth.SignOut();
|
|
CurrentLoginState = LoginState.NotLoggedIn;
|
|
}
|
|
|
|
|
|
|
|
// 获取友好的错误信息
|
|
string GetFriendlyErrorMessage(Exception exception)
|
|
{
|
|
if (exception == null) return "未知错误";
|
|
|
|
var firebaseEx = exception.GetBaseException() as Firebase.FirebaseException;
|
|
return $"{firebaseEx.ErrorCode}:{firebaseEx.Message}";
|
|
}
|
|
public void OnMessageReceived(object sender, Firebase.Messaging.MessageReceivedEventArgs e)
|
|
{
|
|
UnityEngine.Debug.Log("===From: " + e.Message.From);
|
|
UnityEngine.Debug.Log("===Message ID: " + e.Message.MessageId);
|
|
}
|
|
public void OnTokenReceived(object sender, Firebase.Messaging.TokenReceivedEventArgs e)
|
|
{
|
|
UnityEngine.Debug.Log("===Token Revoked"+e.Token);
|
|
}
|
|
|
|
}
|
|
|
|
// 登录状态详细信息类
|
|
public class LoginStateDetail
|
|
{
|
|
public FireBaseCtrl.LoginState State { get; set; }
|
|
public string Description { get; set; }
|
|
public string UserId { get; set; }
|
|
public string DisplayName { get; set; }
|
|
}
|
|
|
|
|
|
} |