283 lines
No EOL
9.3 KiB
C#
283 lines
No EOL
9.3 KiB
C#
using System;
|
|
using System.Threading.Tasks;
|
|
using Firebase;
|
|
using Firebase.Auth;
|
|
using Firebase.Database;
|
|
using UnityEngine;
|
|
|
|
/// <summary>
|
|
/// the general managing class for handling communication with the firebase backend
|
|
/// (to be initialised by GameManager)
|
|
/// </summary>
|
|
public class Backend : MonoBehaviour
|
|
{
|
|
/// <summary>
|
|
/// enum for the result of the authentication process
|
|
/// </summary>
|
|
// ReSharper disable once MemberCanBePrivate.Global
|
|
public enum AuthenticationResult
|
|
{
|
|
Ok,
|
|
AlreadyAuthenticated,
|
|
NonExistentUser,
|
|
AlreadyExistingUser,
|
|
InvalidCredentials,
|
|
GenericError
|
|
}
|
|
|
|
/// <summary>
|
|
/// generic enum for the result of a database transaction
|
|
/// </summary>
|
|
// ReSharper disable once MemberCanBePrivate.Global
|
|
public enum DatabaseTransactionResult
|
|
{
|
|
Ok,
|
|
Unauthenticated,
|
|
Error
|
|
}
|
|
|
|
/// <summary>
|
|
/// enum for the connection status of the firebase backend
|
|
/// </summary>
|
|
public enum FirebaseConnectionStatus
|
|
{
|
|
NotConnected,
|
|
Connected,
|
|
UpdateRequired, // "a required system component is out of date"
|
|
Updating, // "a required system component is updating, retrying in a bit..."
|
|
ExternalError, // "a system component is disabled, invalid, missing, or permissions are insufficient"
|
|
InternalError // "an unknown error occurred"
|
|
}
|
|
|
|
/// <summary>
|
|
/// whether the backend is connected to the firebase backend
|
|
/// </summary>
|
|
public FirebaseConnectionStatus status = FirebaseConnectionStatus.NotConnected;
|
|
|
|
/// <summary>
|
|
/// the firebase authentication object
|
|
/// </summary>
|
|
private FirebaseAuth _auth;
|
|
|
|
/// <summary>
|
|
/// the firebase database reference
|
|
/// </summary>
|
|
private DatabaseReference _db;
|
|
|
|
/// <summary>
|
|
/// callback function to be invoked when the user signs in
|
|
/// </summary>
|
|
private Action<FirebaseUser> _onSignInCallback = user => { Debug.Log("signed in as" + user.UserId); };
|
|
|
|
/// <summary>
|
|
/// callback function to be invoked when the user signs out
|
|
/// </summary>
|
|
private Action<FirebaseUser> _onSignOutCallback = user => { Debug.Log("signed out" + user.UserId); };
|
|
|
|
/// <summary>
|
|
/// the current user object, if authenticated
|
|
/// </summary>
|
|
private FirebaseUser _user;
|
|
|
|
/// <summary>
|
|
/// script load function
|
|
/// </summary>
|
|
private void Awake()
|
|
{
|
|
Debug.Log("firing firebase Initialise() invocation");
|
|
Initialise();
|
|
}
|
|
|
|
/// <summary>
|
|
/// deferred cleanup function
|
|
/// </summary>
|
|
private void OnDestroy()
|
|
{
|
|
SignOutUser();
|
|
_auth.StateChanged -= AuthStateChanged;
|
|
_auth = null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// variable initialisation function
|
|
/// </summary>
|
|
private void Initialise()
|
|
{
|
|
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
|
|
{
|
|
// cher is this robust enough
|
|
switch (task.Result)
|
|
{
|
|
case DependencyStatus.Available:
|
|
var app = FirebaseApp.DefaultInstance;
|
|
_auth = FirebaseAuth.GetAuth(app);
|
|
_auth.StateChanged += AuthStateChanged;
|
|
_db = FirebaseDatabase.DefaultInstance.RootReference;
|
|
status = FirebaseConnectionStatus.Connected;
|
|
break;
|
|
|
|
case DependencyStatus.UnavailableDisabled:
|
|
case DependencyStatus.UnavailableInvalid:
|
|
case DependencyStatus.UnavilableMissing:
|
|
case DependencyStatus.UnavailablePermission:
|
|
status = FirebaseConnectionStatus.ExternalError;
|
|
break;
|
|
|
|
case DependencyStatus.UnavailableUpdating:
|
|
status = FirebaseConnectionStatus.Updating;
|
|
RetryInitialiseAfterDelay();
|
|
break;
|
|
|
|
case DependencyStatus.UnavailableUpdaterequired:
|
|
status = FirebaseConnectionStatus.UpdateRequired;
|
|
break;
|
|
|
|
case DependencyStatus.UnavailableOther:
|
|
default:
|
|
status = FirebaseConnectionStatus.InternalError;
|
|
Debug.LogError("firebase ??? blew up or something," + task.Result);
|
|
break;
|
|
}
|
|
|
|
Debug.Log("firebase status is" + status);
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// function to handle the authentication state change event
|
|
/// </summary>
|
|
/// <param name="sender">the object that triggered the event</param>
|
|
/// <param name="eventArgs">the event arguments</param>
|
|
private void AuthStateChanged(object sender, EventArgs eventArgs)
|
|
{
|
|
// if the user hasn't changed, do nothing
|
|
if (_auth.CurrentUser == _user) return;
|
|
|
|
// if the user has changed, check if they've signed in or out
|
|
var signedIn = _user != _auth.CurrentUser && _auth.CurrentUser != null;
|
|
|
|
// if we're not signed in, but we still hold _user locally, we've signed out
|
|
if (!signedIn && _user != null) _onSignOutCallback(_user);
|
|
|
|
// they have signed in, update _user
|
|
_user = _auth.CurrentUser;
|
|
if (signedIn) _onSignInCallback(_user);
|
|
}
|
|
|
|
/// <summary>
|
|
/// function to register a callback for when the user signs in
|
|
/// </summary>
|
|
/// <param name="callback">callback function that takes in a FirebaseUser argument</param>
|
|
private void RegisterOnSignInCallback(Action<FirebaseUser> callback)
|
|
{
|
|
_onSignInCallback = callback;
|
|
}
|
|
|
|
/// <summary>
|
|
/// function to register a callback for when the user signs out
|
|
/// </summary>
|
|
/// <param name="callback">callback function that takes in a FirebaseUser argument</param>
|
|
private void RegisterOnSignOutCallback(Action<FirebaseUser> callback)
|
|
{
|
|
_onSignOutCallback = callback;
|
|
}
|
|
|
|
/// <summary>
|
|
/// async function to retry initialisation after a delay
|
|
/// </summary>
|
|
private async void RetryInitialiseAfterDelay()
|
|
{
|
|
await Task.Delay(TimeSpan.FromSeconds(10));
|
|
Initialise();
|
|
}
|
|
|
|
/// <summary>
|
|
/// abstraction function to authenticate the user
|
|
/// </summary>
|
|
/// <param name="username">user name string</param>
|
|
/// <param name="password">user raw password string</param>
|
|
/// <param name="callback">callback function that takes in an AuthenticationResult argument</param>
|
|
/// <param name="registerUser">whether to treat authentication as registration</param>
|
|
private void AuthenticateUser(
|
|
string username,
|
|
string password,
|
|
Action<AuthenticationResult> callback,
|
|
bool registerUser = false)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
/// <summary>
|
|
/// abstraction function to retrieve the user
|
|
/// </summary>
|
|
/// <returns>the firebase user object</returns>
|
|
private FirebaseUser GetUser()
|
|
{
|
|
return _user;
|
|
}
|
|
|
|
/// <summary>
|
|
/// abstraction function to sign out the user
|
|
/// </summary>
|
|
private void SignOutUser()
|
|
{
|
|
_auth.SignOut();
|
|
}
|
|
|
|
/// <summary>
|
|
/// abstraction function to submit a play to the database
|
|
/// </summary>
|
|
/// <param name="averageMatchAccuracy">the float percentage (0-100) of how accurate the user was when colour matching</param>
|
|
/// <param name="callback">callback function that takes in one DatabaseTransactionResult argument</param>
|
|
private void SubmitPlay(
|
|
float averageMatchAccuracy,
|
|
Action<DatabaseTransactionResult> callback)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
/// <summary>
|
|
/// abstraction function to get and calculate the user's rating from the database
|
|
/// calculation is done locally, call UpdateUserRating to update the user's rating in the database
|
|
/// </summary>
|
|
/// <param name="callback">callback function that takes in a DatabaseTransactionResult and float (user rating) argument</param>
|
|
private void CalculateUserRating(
|
|
Action<DatabaseTransactionResult, float> callback)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
/// <summary>
|
|
/// abstraction function to update the user's rating in the database
|
|
/// </summary>
|
|
/// <param name="newRating">new user rating value as a float</param>
|
|
/// <param name="callback">callback function that takes in one DatabaseTransactionResult argument</param>
|
|
private void UpdateUserRating(
|
|
float newRating,
|
|
Action<DatabaseTransactionResult> callback)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
/// <summary>
|
|
/// abstraction function to get the leaderboard from the database
|
|
/// </summary>
|
|
/// <param name="callback"></param>
|
|
/// <exception cref="NotImplementedException"></exception>
|
|
private void GetLeaderboard(
|
|
Action<DatabaseTransactionResult, LeaderboardEntry[]> callback)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
/// <summary>
|
|
/// struct for a leaderboard entry
|
|
/// </summary>
|
|
// ReSharper disable once MemberCanBePrivate.Global
|
|
public struct LeaderboardEntry
|
|
{
|
|
public string Username;
|
|
public float Rating;
|
|
public int PlayCount;
|
|
}
|
|
} |