This repository has been archived on 2024-11-20. You can view files and clone it, but cannot push or open issues or pull requests.
colourmeok/ColourMeOKGame/Assets/Scripts/Backend.cs
2024-11-15 07:54:43 +08:00

291 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>
public enum AuthenticationResult
{
Ok,
AlreadyAuthenticated,
NonExistentUser,
AlreadyExistingUser,
InvalidCredentials,
GenericError
}
/// <summary>
/// generic enum for the result of a database transaction
/// </summary>
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:
_auth = FirebaseAuth.GetAuth(FirebaseApp.DefaultInstance);
_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="playData">play data</param>
/// <param name="callback">callback function that takes in one DatabaseTransactionResult argument</param>
private void SubmitPlay(
PlayData playData,
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>
public struct LeaderboardEntry
{
public string Username;
public float Rating;
public int PlayCount;
}
/// <summary>
/// struct for play data
/// </summary>
public struct PlayData
{
public int RoundsPlayed;
public float AverageOverallAccuracy;
public float AverageLuminanceAccuracy;
public float AverageRedGreenAccuracy;
public float AverageBlueYellowAccuracy;
}
}