Supercell.GUT/Supercell.GUT.Server/Document/DocumentManager.cs

86 lines
3.2 KiB
C#
Raw Normal View History

using MongoDB.Driver;
using Supercell.GUT.Server.Database;
using Supercell.GUT.Server.Database.Document;
using Supercell.GUT.Server.Util;
using Supercell.GUT.Titan.Logic.Math;
namespace Supercell.GUT.Server.Document;
internal class DocumentManager
{
private const string AccountCollectionName = "t_account_info";
private const string AvatarCollectionName = "t_player_avatar";
private const string AccountIdCounterName = "AccountId";
private readonly DatabaseManager _databaseManager;
public LogicLong Id { get; private set; } = new();
public AccountDocument? AccountDocument { get; private set; }
public AvatarDocument? AvatarDocument { get; private set; }
public DocumentManager(DatabaseManager databaseManager)
{
_databaseManager = databaseManager;
}
public async Task SaveAsync()
{
if (AccountDocument != null)
{
IMongoCollection<AccountDocument> accountCollection = _databaseManager.GetCollection<AccountDocument>(AccountCollectionName);
await accountCollection.ReplaceOneAsync(doc => doc.DocumentId.Equals(AccountDocument.DocumentId), AccountDocument);
}
if (AvatarDocument != null)
{
AvatarDocument.LastSaveTime = TimeUtil.GetCurrentTimestamp();
IMongoCollection<AvatarDocument> avatarCollection = _databaseManager.GetCollection<AvatarDocument>(AvatarCollectionName);
await avatarCollection.ReplaceOneAsync(doc => doc.DocumentId.Equals(AvatarDocument.DocumentId), AvatarDocument);
}
}
public async Task CreateAccount()
{
if (AccountDocument != null) throw new InvalidOperationException("DocumentManager::CreateAccount: called when AccountDocument already created!");
int lowId = await _databaseManager.GetNextLowIdAsync(AccountIdCounterName);
AccountDocument = new(new(0, lowId), "ToDoRandomToken");
IMongoCollection<AccountDocument> accountCollection = _databaseManager.GetCollection<AccountDocument>(AccountCollectionName);
await accountCollection.InsertOneAsync(AccountDocument);
Id = AccountDocument.DocumentId;
}
public async Task EnsureAccountDocument()
{
if (AccountDocument != null) return;
IMongoCollection<AccountDocument> accountCollection = _databaseManager.GetCollection<AccountDocument>(AccountCollectionName);
AccountDocument = await (await accountCollection.FindAsync(document => document.DocumentId.Equals(Id))).SingleOrDefaultAsync();
}
public async Task EnsureAvatarDocument()
{
if (AvatarDocument != null) return;
IMongoCollection<AvatarDocument> avatarCollection = _databaseManager.GetCollection<AvatarDocument>(AvatarCollectionName);
AvatarDocument = await (await avatarCollection.FindAsync(document => document.DocumentId.Equals(Id))).SingleOrDefaultAsync();
if (AvatarDocument == null)
{
AvatarDocument = new(Id);
await avatarCollection.InsertOneAsync(AvatarDocument);
}
}
public void SetDocumentId(LogicLong id)
{
if (Id.LowerInt > 0) throw new InvalidOperationException("DocumentManager::SetDocumentId: trying to override Id.");
Id = id;
}
}