btcpayserver/BTCPayServer/HostedServices/RatesHostedService.cs

68 lines
2.5 KiB
C#
Raw Normal View History

using System;
2018-04-15 14:18:51 +02:00
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Services;
using BTCPayServer.Services.Rates;
using Microsoft.Extensions.Hosting;
2018-04-15 14:18:51 +02:00
using BTCPayServer.Logging;
using System.Runtime.CompilerServices;
2018-04-23 09:09:18 +02:00
using System.IO;
using System.Text;
namespace BTCPayServer.HostedServices
{
public class RatesHostedService : BaseAsyncService
{
private SettingsRepository _SettingsRepository;
2018-04-15 14:18:51 +02:00
private IRateProviderFactory _RateProviderFactory;
private CoinAverageSettings _coinAverageSettings;
public RatesHostedService(SettingsRepository repo,
CoinAverageSettings coinAverageSettings,
2018-04-15 14:18:51 +02:00
IRateProviderFactory rateProviderFactory)
{
this._SettingsRepository = repo;
2018-04-15 14:18:51 +02:00
_RateProviderFactory = rateProviderFactory;
_coinAverageSettings = coinAverageSettings;
}
internal override Task[] initializeTasks()
2018-04-15 14:18:51 +02:00
{
return new[]
{
createLoopTask(RefreshCoinAverageSupportedExchanges),
createLoopTask(RefreshCoinAverageSettings)
};
2018-04-15 14:18:51 +02:00
}
async Task RefreshCoinAverageSupportedExchanges()
{
2018-04-19 09:54:25 +02:00
await new SynchronizationContextRemover();
var tickers = await new CoinAverageRateProvider("BTC") { Authenticator = _coinAverageSettings }.GetExchangeTickersAsync();
_coinAverageSettings.AvailableExchanges = tickers
.Exchanges
.Select(c => (c.DisplayName, c.Name))
.ToArray();
await Task.Delay(TimeSpan.FromHours(5), _SyncToken);
}
async Task RefreshCoinAverageSettings()
{
await new SynchronizationContextRemover();
var rates = (await _SettingsRepository.GetSettingAsync<RatesSetting>()) ?? new RatesSetting();
_RateProviderFactory.CacheSpan = TimeSpan.FromMinutes(rates.CacheInMinutes);
if (!string.IsNullOrWhiteSpace(rates.PrivateKey) && !string.IsNullOrWhiteSpace(rates.PublicKey))
{
_coinAverageSettings.KeyPair = (rates.PublicKey, rates.PrivateKey);
}
else
{
_coinAverageSettings.KeyPair = null;
}
await _SettingsRepository.WaitSettingsChanged<RatesSetting>(_SyncToken);
}
}
}