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

467 lines
16 KiB
C#
Raw Normal View History

2024-11-15 04:15:45 +08:00
using System;
2024-11-17 07:29:22 +08:00
using System.Collections.Generic;
2024-11-15 04:15:45 +08:00
using System.Threading.Tasks;
using Firebase;
using Firebase.Auth;
using Firebase.Database;
2024-11-17 07:29:22 +08:00
using Firebase.Extensions;
2024-11-15 04:15:45 +08:00
using UnityEngine;
/// <summary>
/// the general managing class for handling communication with the firebase backend
/// (to be initialised by GameManager)
/// </summary>
2024-11-17 07:29:22 +08:00
public class Backend
2024-11-15 04:15:45 +08:00
{
/// <summary>
/// enum for the result of the authentication process
/// </summary>
public enum AuthenticationResult
{
Ok,
AlreadyAuthenticated,
NonExistentUser,
AlreadyExistingUser,
2024-11-17 07:29:22 +08:00
InvalidEmail,
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"
}
2024-11-15 04:15:45 +08:00
/// <summary>
2024-11-17 07:29:22 +08:00
/// callback functions to be invoked when the user signs in
2024-11-15 04:15:45 +08:00
/// </summary>
2024-11-17 07:29:22 +08:00
private readonly List<Action<FirebaseUser>> _onSignInCallback = new();
/// <summary>
/// callback functions to be invoked when the user signs out
/// </summary>
private readonly List<Action<FirebaseUser>> _onSignOutCallback = new();
2024-11-15 04:15:45 +08:00
/// <summary>
/// the firebase authentication object
/// </summary>
private FirebaseAuth _auth;
/// <summary>
/// the firebase database reference
/// </summary>
private DatabaseReference _db;
/// <summary>
/// the current user object, if authenticated
/// </summary>
private FirebaseUser _user;
/// <summary>
2024-11-17 07:29:22 +08:00
/// the current user's username, if authenticated
2024-11-15 04:15:45 +08:00
/// </summary>
2024-11-17 07:29:22 +08:00
private string _username;
2024-11-15 04:15:45 +08:00
/// <summary>
2024-11-17 07:29:22 +08:00
/// whether the backend is connected to the firebase backend
2024-11-15 04:15:45 +08:00
/// </summary>
2024-11-17 07:29:22 +08:00
public FirebaseConnectionStatus Status = FirebaseConnectionStatus.NotConnected;
2024-11-15 04:15:45 +08:00
/// <summary>
/// variable initialisation function
/// </summary>
2024-11-17 07:29:22 +08:00
public void Initialise()
2024-11-15 04:15:45 +08:00
{
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
// cher is this robust enough
2024-11-15 04:15:45 +08:00
switch (task.Result)
{
case DependencyStatus.Available:
2024-11-15 07:54:43 +08:00
_auth = FirebaseAuth.GetAuth(FirebaseApp.DefaultInstance);
2024-11-15 04:15:45 +08:00
_auth.StateChanged += AuthStateChanged;
_db = FirebaseDatabase.DefaultInstance.RootReference;
2024-11-17 07:29:22 +08:00
Status = FirebaseConnectionStatus.Connected;
2024-11-15 04:15:45 +08:00
break;
case DependencyStatus.UnavailableDisabled:
case DependencyStatus.UnavailableInvalid:
case DependencyStatus.UnavilableMissing:
case DependencyStatus.UnavailablePermission:
2024-11-17 07:29:22 +08:00
Status = FirebaseConnectionStatus.ExternalError;
2024-11-15 04:15:45 +08:00
break;
case DependencyStatus.UnavailableUpdating:
2024-11-17 07:29:22 +08:00
Status = FirebaseConnectionStatus.Updating;
2024-11-15 04:15:45 +08:00
RetryInitialiseAfterDelay();
break;
case DependencyStatus.UnavailableUpdaterequired:
2024-11-17 07:29:22 +08:00
Status = FirebaseConnectionStatus.UpdateRequired;
break;
2024-11-15 04:15:45 +08:00
case DependencyStatus.UnavailableOther:
default:
2024-11-17 07:29:22 +08:00
Status = FirebaseConnectionStatus.InternalError;
2024-11-15 04:15:45 +08:00
Debug.LogError("firebase ??? blew up or something," + task.Result);
break;
}
2024-11-17 07:29:22 +08:00
Debug.Log("firebase status is" + Status);
2024-11-15 04:15:45 +08:00
});
}
2024-11-17 07:29:22 +08:00
/// <summary>
/// async function to retry initialisation after a delay
/// </summary>
private async void RetryInitialiseAfterDelay()
{
await Task.Delay(TimeSpan.FromSeconds(10));
Initialise();
}
/// <summary>
/// cleanup function
/// </summary>
public void Cleanup()
{
SignOutUser();
_auth.StateChanged -= AuthStateChanged;
_auth = null;
}
2024-11-15 04:15:45 +08:00
/// <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
2024-11-15 04:15:45 +08:00
if (_auth.CurrentUser == _user) return;
// if the user has changed, check if they've signed in or out
2024-11-15 04:15:45 +08:00
var signedIn = _user != _auth.CurrentUser && _auth.CurrentUser != null;
// if we're not signed in, but we still hold _user locally, we've signed out
2024-11-17 07:29:22 +08:00
if (!signedIn && _user != null)
{
Debug.Log($"signed out successfully as {_user.UserId}");
foreach (var callback in _onSignOutCallback)
callback(_user);
}
// they have signed in, update _user
_user = _auth.CurrentUser;
2024-11-17 07:29:22 +08:00
if (signedIn)
{
Debug.Log($"signed in successfully as {_user.UserId}");
RetrieveUsername();
foreach (var callback in _onSignInCallback) callback(_user);
}
2024-11-15 04:15:45 +08:00
}
/// <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>
2024-11-17 07:29:22 +08:00
public void RegisterOnSignInCallback(Action<FirebaseUser> callback)
2024-11-15 04:15:45 +08:00
{
2024-11-17 07:29:22 +08:00
_onSignInCallback.Add(callback);
2024-11-15 04:15:45 +08:00
}
/// <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>
2024-11-17 07:29:22 +08:00
public void RegisterOnSignOutCallback(Action<FirebaseUser> callback)
2024-11-15 04:15:45 +08:00
{
2024-11-17 07:29:22 +08:00
_onSignOutCallback.Add(callback);
2024-11-15 04:15:45 +08:00
}
/// <summary>
/// abstraction function to authenticate the user
/// </summary>
2024-11-17 07:29:22 +08:00
/// <param name="email">email string</param>
2024-11-15 04:15:45 +08:00
/// <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>
2024-11-17 07:29:22 +08:00
/// <param name="registeringUsername">username string if registering</param>
public void AuthenticateUser(
string email,
2024-11-15 04:15:45 +08:00
string password,
Action<AuthenticationResult> callback,
2024-11-17 07:29:22 +08:00
bool registerUser = false,
string registeringUsername = "")
2024-11-15 04:15:45 +08:00
{
2024-11-17 07:29:22 +08:00
if (GameManager.Instance.Backend.GetUser() != null)
{
callback(AuthenticationResult.AlreadyAuthenticated);
return;
}
if (registerUser)
{
// register user
_auth.CreateUserWithEmailAndPasswordAsync(email, password)
.ContinueWithOnMainThread(createTask =>
{
if (createTask.IsCompletedSuccessfully)
{
// store username
_db.Child("users")
.Child(_user.UserId)
.Child("username")
.SetValueAsync(registeringUsername)
.ContinueWithOnMainThread(setUsernameTask =>
{
if (setUsernameTask.IsCompletedSuccessfully)
{
_username = registeringUsername;
callback(AuthenticationResult.Ok);
}
else
{
Debug.LogError(setUsernameTask.Exception);
callback(AuthenticationResult.GenericError);
}
});
return;
}
if (createTask.Exception?.InnerException == null)
{
callback(AuthenticationResult.GenericError);
return;
}
var error = (AuthError)((FirebaseException)createTask.Exception.InnerException).ErrorCode;
// ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault
switch (error)
{
case AuthError.UserNotFound:
callback(AuthenticationResult.NonExistentUser);
return;
case AuthError.InvalidEmail:
callback(AuthenticationResult.InvalidEmail);
return;
case AuthError.WeakPassword:
case AuthError.InvalidCredential:
callback(AuthenticationResult.InvalidCredentials);
return;
case AuthError.AccountExistsWithDifferentCredentials:
case AuthError.EmailAlreadyInUse:
callback(AuthenticationResult.AlreadyExistingUser);
return;
case AuthError.Failure:
default:
Debug.LogError(error);
Debug.LogError(createTask.Exception);
callback(AuthenticationResult.GenericError);
break;
}
});
return;
}
_auth.SignInWithEmailAndPasswordAsync(email, password)
.ContinueWithOnMainThread(signInTask =>
{
if (signInTask.IsCompletedSuccessfully)
{
callback(AuthenticationResult.Ok);
return;
}
if (signInTask.Exception?.InnerException == null)
{
callback(AuthenticationResult.GenericError);
return;
}
var error = (AuthError)((FirebaseException)signInTask.Exception.InnerException).ErrorCode;
// ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault
switch (error)
{
case AuthError.UserNotFound:
callback(AuthenticationResult.NonExistentUser);
return;
case AuthError.InvalidEmail:
callback(AuthenticationResult.InvalidEmail);
return;
case AuthError.WeakPassword:
case AuthError.InvalidCredential:
callback(AuthenticationResult.InvalidCredentials);
return;
case AuthError.AccountExistsWithDifferentCredentials:
case AuthError.EmailAlreadyInUse:
callback(AuthenticationResult.AlreadyExistingUser);
return;
case AuthError.Failure:
default:
Debug.LogError(error);
Debug.LogError(signInTask.Exception);
callback(AuthenticationResult.GenericError);
break;
}
});
}
/// <summary>
/// function to retrieve the user's username from the database
/// </summary>
private void RetrieveUsername()
{
if (!Status.Equals(FirebaseConnectionStatus.Connected)) return;
_db.Child("users").Child(_user.UserId).Child("username").GetValueAsync().ContinueWith(task =>
{
if (task.IsCompletedSuccessfully)
{
_username = task.Result.Value.ToString();
Debug.Log($"our username is {_username}");
}
else
{
_username = "???";
Debug.LogError("failed to get username");
}
});
2024-11-15 04:15:45 +08:00
}
/// <summary>
/// abstraction function to retrieve the user
/// </summary>
/// <returns>the firebase user object</returns>
2024-11-17 07:29:22 +08:00
public FirebaseUser GetUser()
2024-11-15 04:15:45 +08:00
{
return _user;
}
2024-11-17 07:29:22 +08:00
public string GetUsername()
{
return _username;
}
2024-11-15 04:15:45 +08:00
/// <summary>
/// abstraction function to sign out the user
/// </summary>
2024-11-17 07:29:22 +08:00
public void SignOutUser()
2024-11-15 04:15:45 +08:00
{
_auth.SignOut();
}
/// <summary>
/// abstraction function to submit a play to the database
/// </summary>
/// <param name="playData">play data</param>
2024-11-15 04:15:45 +08:00
/// <param name="callback">callback function that takes in one DatabaseTransactionResult argument</param>
2024-11-17 07:29:22 +08:00
public void SubmitPlay(
PlayData playData,
2024-11-15 04:15:45 +08:00
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>
2024-11-17 07:29:22 +08:00
public void CalculateUserRating(
2024-11-15 04:15:45 +08:00
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>
2024-11-17 07:29:22 +08:00
public void UpdateUserRating(
2024-11-15 04:15:45 +08:00
float newRating,
Action<DatabaseTransactionResult> callback)
{
throw new NotImplementedException();
}
/// <summary>
/// abstraction function to get the leaderboard from the database
/// </summary>
2024-11-17 07:29:22 +08:00
/// <param name="callback">
/// callback function that takes in a DatabaseTransactionResult and LeaderboardEntry[] argument
/// </param>
public void GetLeaderboard(
2024-11-15 04:15:45 +08:00
Action<DatabaseTransactionResult, LeaderboardEntry[]> callback)
{
throw new NotImplementedException();
}
2024-11-17 07:29:22 +08:00
// private void Playground()
// {
// // update username
// _db.Child("users").Child(_user.UserId).Child("username").SetValueAsync("newusername").ContinueWith(task => { });
//
// // update email
// _user.SendEmailVerificationBeforeUpdatingEmailAsync("name@example.com").ContinueWith(task => { });
//
// // update password
// _user.UpdatePasswordAsync("password").ContinueWith(task => { });
//
// // reset password
// _auth.SendPasswordResetEmailAsync("name@example.com").ContinueWith(task => { });
// }
2024-11-15 04:15:45 +08:00
/// <summary>
/// struct for a leaderboard entry
/// </summary>
public struct LeaderboardEntry
{
public string Username;
public float Rating;
public int PlayCount;
2024-11-17 07:29:22 +08:00
public LeaderboardEntry(string username, float rating, int playCount)
{
Username = username;
Rating = rating;
PlayCount = playCount;
}
2024-11-15 04:15:45 +08:00
}
/// <summary>
/// struct for play data
/// </summary>
public struct PlayData
{
public int RoundsPlayed;
public float AverageOverallAccuracy;
2024-11-17 07:29:22 +08:00
public float AverageLightnessAccuracy;
public float AverageChromaAccuracy;
public float AverageHueAccuracy;
}
2024-11-15 04:15:45 +08:00
}