Luski.Net/Luski.net/API.cs

96 lines
2.8 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Luski.net.Enums;
namespace Luski.net;
public class API
{
[JsonIgnore]
public MainServer MainServer { get; internal set; }
public bool IsAnyServerLoggedin { get; internal set; }
internal List<PublicServer> InternalServers { get; } = new();
public IReadOnlyList<PublicServer> LoadedServers => InternalServers.AsReadOnly();
public Task<bool> TryGetPublicServer(out PublicServer Server, string Domain, string Version = "v1",
bool Secure = true)
{
try
{
Task<PublicServer> result = GetPublicServer(Domain, Version, Secure);
Task.WaitAll(result);
Server = result.Result;
return Task.FromResult(true);
}
catch (Exception e)
{
Console.WriteLine(e);
Server = null!;
return Task.FromResult(false);
}
}
public async Task<PublicServer> GetPublicServer(string Domain, string Version = "v1", bool Secure = true)
{
PublicServer s;
try
{
IEnumerable<PublicServer> isl = InternalServers.Where(a => (a.Domain == Domain && a.ApiVersion == Version));
if (isl.Any()) return isl.First();
s = await PublicServer.GetServer(Domain, Version, Secure);
}
catch (Exception e)
{
Console.WriteLine("Failed to connect to public server '{0}' using API {1}. No alternate server was found.", Domain, Version);
throw;
}
string? f = s.Storage.GetStorageDirectory(StorageDirectory.StorageInfo) + "token";
if (File.Exists(f))
{
f = File.ReadAllText(f);
}
else f = null;
try
{
if (f is not null)
{
bool b = await s.LoginViaToken(f);
if (b)
{
Console.WriteLine("Auto Login Successful");
IsAnyServerLoggedin = true;
}
else
{
s.Token = null;
s.Error = null;
}
}
}
catch
{
}
InternalServers.Add(s);
return s;
}
public MainServer GetMainServer(string Domain, string Version = "v1")
{
DateTime dt = DateTime.UtcNow;
Console.WriteLine("Conecting to main server '{0}' using API {1}.", Domain, Version);
MainServer = new(Domain, Version)
{
ServerType = ServerType.Main
};
Console.WriteLine("Connected to main server '{0}' using API {1} in {2}.", Domain, Version, DateTime.UtcNow.Subtract(dt).ToString("g"));
return MainServer;
}
}