//
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace MUnique.OpenMU.Web.API
{
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using MUnique.OpenMU.DataModel.Entities;
using MUnique.OpenMU.GameLogic;
using MUnique.OpenMU.GameServer;
using MUnique.OpenMU.Interfaces;
using MUnique.OpenMU.Persistence;
///
/// Server API controller.
///
[Route("api/")]
public class ServerController : Controller
{
private IDictionary _gameServers;
///
/// Initializes a new instance of the class.
///
/// The game servers.
public ServerController(IDictionary gameServers) => this._gameServers = gameServers;
///
/// Sends a global message to the specified server.
///
/// The server id.
/// The message.
[Route("send/{id=0}")]
public async Task SendGlobalMessage(int id, [FromQuery(Name = "msg")] string msg)
{
var server = (GameServer)this._gameServers.Values.ElementAt(id);
if (server is not null)
{
await server.Context.SendGlobalNotificationAsync(msg).ConfigureAwait(false);
return this.Ok("Done");
}
return this.Ok("Server not ready");
}
///
/// Gets a flag, if the specified account is currently online.
///
/// Name of the account.
/// True, when online.
[HttpGet]
[Route("is-online/{accountName=0}")]
public async Task GetIsOnlineAsync(string accountName)
{
var isOnline = false;
foreach (var server in this._gameServers.Values.OfType())
{
var players = await server.Context.GetPlayersAsync().ConfigureAwait(false);
if (players.Any(p => p.Account?.LoginName == accountName))
{
isOnline = true;
break;
}
}
return isOnline;
}
///
/// Gets the server state.
///
[HttpGet]
[Route("status")]
public IActionResult ServerState()
{
int sum = 0;
var list = new List();
this._gameServers.Values.ForEach(async item =>
{
var server = item as GameServer;
if (server is not null)
{
await server.Context.ForEachPlayerAsync(player =>
{
list.Add(player.GetName());
return Task.CompletedTask;
}).ConfigureAwait(false);
sum = sum + server.Context.PlayerCount;
}
});
var item = new
{
state = "Online",
players = sum,
playersList = list,
};
return this.Ok(JsonSerializer.Serialize(item));
}
}
}