92 lines
No EOL
1.7 KiB
C#
92 lines
No EOL
1.7 KiB
C#
using JellyGlass.Exceptions;
|
|
using JellyGlass.Models;
|
|
using JellyGlass.Repositories;
|
|
|
|
namespace JellyGlass.Services;
|
|
|
|
public class ClientService : IClientService
|
|
{
|
|
private IServerRepository _repository;
|
|
private static List<JellyfinApiClient> _clients = new List<JellyfinApiClient>();
|
|
private ILogger<ClientService> _logger;
|
|
|
|
public ClientService(IServerRepository repository, ILogger<ClientService> logger)
|
|
{
|
|
_repository = repository;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task<JellyfinApiClient[]> GetClients()
|
|
{
|
|
if (!_clients.Any())
|
|
{
|
|
await LoadClients();
|
|
}
|
|
|
|
return _clients.ToArray();
|
|
}
|
|
|
|
public async Task<JellyfinApiClient> GetClientFromUrl(string url)
|
|
{
|
|
if (!_clients.Any())
|
|
{
|
|
await LoadClients();
|
|
}
|
|
|
|
var client = _clients.FirstOrDefault(c => c.InstanceUrl == url);
|
|
|
|
if (client == null)
|
|
{
|
|
throw new Exception($"Could not find client with url {url}");
|
|
}
|
|
|
|
return client;
|
|
}
|
|
|
|
public async Task LoadNewClient(Server server)
|
|
{
|
|
var client = new JellyfinApiClient(server.Url, server.ApiToken);
|
|
|
|
try
|
|
{
|
|
await client.GetServerInfo();
|
|
}
|
|
catch (JellyfinApiClientException e)
|
|
{
|
|
_logger.LogError($"Error authenticating to {server.Url}. Error: {e.Message} Client will not be used");
|
|
throw;
|
|
}
|
|
|
|
_clients.Add(client);
|
|
}
|
|
|
|
public void UnloadClient(JellyfinApiClient client)
|
|
{
|
|
if (_clients.Contains(client))
|
|
{
|
|
_clients.Remove(client);
|
|
}
|
|
else
|
|
{
|
|
throw new Exception($"Haven't loaded Jellyfin api client with ID of {client.ID}");
|
|
}
|
|
}
|
|
|
|
private async Task LoadClients()
|
|
{
|
|
var servers = await _repository.GetServers();
|
|
|
|
foreach (var server in servers)
|
|
{
|
|
try
|
|
{
|
|
await LoadNewClient(server);
|
|
}
|
|
catch (JellyfinApiClientException)
|
|
{
|
|
continue;
|
|
}
|
|
}
|
|
|
|
}
|
|
} |