Merge branch '2.0.2' into mcdf-background-creation
This commit is contained in:
@@ -154,4 +154,5 @@ public class LightlessConfig : ILightlessConfiguration
|
|||||||
public bool SyncshellFinderEnabled { get; set; } = false;
|
public bool SyncshellFinderEnabled { get; set; } = false;
|
||||||
public string? SelectedFinderSyncshell { get; set; } = null;
|
public string? SelectedFinderSyncshell { get; set; } = null;
|
||||||
public string LastSeenVersion { get; set; } = string.Empty;
|
public string LastSeenVersion { get; set; } = string.Empty;
|
||||||
|
public HashSet<Guid> OrphanableTempCollections { get; set; } = [];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ internal sealed class PairHandlerAdapter : DisposableMediatorSubscriberBase, IPa
|
|||||||
private readonly TextureDownscaleService _textureDownscaleService;
|
private readonly TextureDownscaleService _textureDownscaleService;
|
||||||
private readonly PairStateCache _pairStateCache;
|
private readonly PairStateCache _pairStateCache;
|
||||||
private readonly PairPerformanceMetricsCache _performanceMetricsCache;
|
private readonly PairPerformanceMetricsCache _performanceMetricsCache;
|
||||||
|
private readonly PenumbraTempCollectionJanitor _tempCollectionJanitor;
|
||||||
private readonly PairManager _pairManager;
|
private readonly PairManager _pairManager;
|
||||||
private CancellationTokenSource? _applicationCancellationTokenSource;
|
private CancellationTokenSource? _applicationCancellationTokenSource;
|
||||||
private Guid _applicationId;
|
private Guid _applicationId;
|
||||||
@@ -181,7 +182,8 @@ internal sealed class PairHandlerAdapter : DisposableMediatorSubscriberBase, IPa
|
|||||||
ServerConfigurationManager serverConfigManager,
|
ServerConfigurationManager serverConfigManager,
|
||||||
TextureDownscaleService textureDownscaleService,
|
TextureDownscaleService textureDownscaleService,
|
||||||
PairStateCache pairStateCache,
|
PairStateCache pairStateCache,
|
||||||
PairPerformanceMetricsCache performanceMetricsCache) : base(logger, mediator)
|
PairPerformanceMetricsCache performanceMetricsCache,
|
||||||
|
PenumbraTempCollectionJanitor tempCollectionJanitor) : base(logger, mediator)
|
||||||
{
|
{
|
||||||
_pairManager = pairManager;
|
_pairManager = pairManager;
|
||||||
Ident = ident;
|
Ident = ident;
|
||||||
@@ -199,7 +201,7 @@ internal sealed class PairHandlerAdapter : DisposableMediatorSubscriberBase, IPa
|
|||||||
_textureDownscaleService = textureDownscaleService;
|
_textureDownscaleService = textureDownscaleService;
|
||||||
_pairStateCache = pairStateCache;
|
_pairStateCache = pairStateCache;
|
||||||
_performanceMetricsCache = performanceMetricsCache;
|
_performanceMetricsCache = performanceMetricsCache;
|
||||||
LastAppliedDataBytes = -1;
|
_tempCollectionJanitor = tempCollectionJanitor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Initialize()
|
public void Initialize()
|
||||||
@@ -422,6 +424,7 @@ internal sealed class PairHandlerAdapter : DisposableMediatorSubscriberBase, IPa
|
|||||||
{
|
{
|
||||||
_penumbraCollection = created;
|
_penumbraCollection = created;
|
||||||
_pairStateCache.StoreTemporaryCollection(Ident, created);
|
_pairStateCache.StoreTemporaryCollection(Ident, created);
|
||||||
|
_tempCollectionJanitor.Register(created);
|
||||||
}
|
}
|
||||||
|
|
||||||
return _penumbraCollection;
|
return _penumbraCollection;
|
||||||
@@ -454,6 +457,7 @@ internal sealed class PairHandlerAdapter : DisposableMediatorSubscriberBase, IPa
|
|||||||
_needsCollectionRebuild = true;
|
_needsCollectionRebuild = true;
|
||||||
_forceFullReapply = true;
|
_forceFullReapply = true;
|
||||||
_forceApplyMods = true;
|
_forceApplyMods = true;
|
||||||
|
_tempCollectionJanitor.Unregister(toRelease);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!releaseFromPenumbra || toRelease == Guid.Empty || !_ipcManager.Penumbra.APIAvailable)
|
if (!releaseFromPenumbra || toRelease == Guid.Empty || !_ipcManager.Penumbra.APIAvailable)
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ internal sealed class PairHandlerAdapterFactory : IPairHandlerAdapterFactory
|
|||||||
private readonly TextureDownscaleService _textureDownscaleService;
|
private readonly TextureDownscaleService _textureDownscaleService;
|
||||||
private readonly PairStateCache _pairStateCache;
|
private readonly PairStateCache _pairStateCache;
|
||||||
private readonly PairPerformanceMetricsCache _pairPerformanceMetricsCache;
|
private readonly PairPerformanceMetricsCache _pairPerformanceMetricsCache;
|
||||||
|
private readonly PenumbraTempCollectionJanitor _tempCollectionJanitor;
|
||||||
|
|
||||||
public PairHandlerAdapterFactory(
|
public PairHandlerAdapterFactory(
|
||||||
ILoggerFactory loggerFactory,
|
ILoggerFactory loggerFactory,
|
||||||
@@ -48,7 +49,8 @@ internal sealed class PairHandlerAdapterFactory : IPairHandlerAdapterFactory
|
|||||||
ServerConfigurationManager serverConfigManager,
|
ServerConfigurationManager serverConfigManager,
|
||||||
TextureDownscaleService textureDownscaleService,
|
TextureDownscaleService textureDownscaleService,
|
||||||
PairStateCache pairStateCache,
|
PairStateCache pairStateCache,
|
||||||
PairPerformanceMetricsCache pairPerformanceMetricsCache)
|
PairPerformanceMetricsCache pairPerformanceMetricsCache,
|
||||||
|
PenumbraTempCollectionJanitor tempCollectionJanitor)
|
||||||
{
|
{
|
||||||
_loggerFactory = loggerFactory;
|
_loggerFactory = loggerFactory;
|
||||||
_mediator = mediator;
|
_mediator = mediator;
|
||||||
@@ -66,6 +68,7 @@ internal sealed class PairHandlerAdapterFactory : IPairHandlerAdapterFactory
|
|||||||
_textureDownscaleService = textureDownscaleService;
|
_textureDownscaleService = textureDownscaleService;
|
||||||
_pairStateCache = pairStateCache;
|
_pairStateCache = pairStateCache;
|
||||||
_pairPerformanceMetricsCache = pairPerformanceMetricsCache;
|
_pairPerformanceMetricsCache = pairPerformanceMetricsCache;
|
||||||
|
_tempCollectionJanitor = tempCollectionJanitor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public IPairHandlerAdapter Create(string ident)
|
public IPairHandlerAdapter Create(string ident)
|
||||||
@@ -91,6 +94,7 @@ internal sealed class PairHandlerAdapterFactory : IPairHandlerAdapterFactory
|
|||||||
_serverConfigManager,
|
_serverConfigManager,
|
||||||
_textureDownscaleService,
|
_textureDownscaleService,
|
||||||
_pairStateCache,
|
_pairStateCache,
|
||||||
_pairPerformanceMetricsCache);
|
_pairPerformanceMetricsCache,
|
||||||
|
_tempCollectionJanitor);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ using System.Reflection;
|
|||||||
using OtterTex;
|
using OtterTex;
|
||||||
using LightlessSync.Services.LightFinder;
|
using LightlessSync.Services.LightFinder;
|
||||||
using LightlessSync.Services.PairProcessing;
|
using LightlessSync.Services.PairProcessing;
|
||||||
|
using LightlessSync.UI.Models;
|
||||||
|
|
||||||
namespace LightlessSync;
|
namespace LightlessSync;
|
||||||
|
|
||||||
@@ -135,6 +136,7 @@ public sealed class Plugin : IDalamudPlugin
|
|||||||
services.AddSingleton<ZoneChatService>();
|
services.AddSingleton<ZoneChatService>();
|
||||||
services.AddSingleton<IdDisplayHandler>();
|
services.AddSingleton<IdDisplayHandler>();
|
||||||
services.AddSingleton<PlayerPerformanceService>();
|
services.AddSingleton<PlayerPerformanceService>();
|
||||||
|
services.AddSingleton<PenumbraTempCollectionJanitor>();
|
||||||
|
|
||||||
services.AddSingleton<TextureMetadataHelper>(sp =>
|
services.AddSingleton<TextureMetadataHelper>(sp =>
|
||||||
new TextureMetadataHelper(sp.GetRequiredService<ILogger<TextureMetadataHelper>>(), gameData));
|
new TextureMetadataHelper(sp.GetRequiredService<ILogger<TextureMetadataHelper>>(), gameData));
|
||||||
@@ -299,7 +301,10 @@ public sealed class Plugin : IDalamudPlugin
|
|||||||
sp.GetRequiredService<LightFinderScannerService>(),
|
sp.GetRequiredService<LightFinderScannerService>(),
|
||||||
sp.GetRequiredService<LightFinderService>(),
|
sp.GetRequiredService<LightFinderService>(),
|
||||||
sp.GetRequiredService<LightlessProfileManager>(),
|
sp.GetRequiredService<LightlessProfileManager>(),
|
||||||
sp.GetRequiredService<LightlessMediator>()));
|
sp.GetRequiredService<LightlessMediator>(),
|
||||||
|
chatGui,
|
||||||
|
sp.GetRequiredService<NotificationService>())
|
||||||
|
);
|
||||||
|
|
||||||
// IPC callers / manager
|
// IPC callers / manager
|
||||||
services.AddSingleton(sp => new IpcCallerPenumbra(
|
services.AddSingleton(sp => new IpcCallerPenumbra(
|
||||||
|
|||||||
@@ -4,21 +4,22 @@ using Dalamud.Plugin;
|
|||||||
using Dalamud.Plugin.Services;
|
using Dalamud.Plugin.Services;
|
||||||
using LightlessSync.LightlessConfiguration;
|
using LightlessSync.LightlessConfiguration;
|
||||||
using LightlessSync.LightlessConfiguration.Models;
|
using LightlessSync.LightlessConfiguration.Models;
|
||||||
|
using LightlessSync.Services.LightFinder;
|
||||||
using LightlessSync.Services.Mediator;
|
using LightlessSync.Services.Mediator;
|
||||||
|
using LightlessSync.UI;
|
||||||
|
using LightlessSync.UI.Services;
|
||||||
using LightlessSync.Utils;
|
using LightlessSync.Utils;
|
||||||
using LightlessSync.WebAPI;
|
using LightlessSync.WebAPI;
|
||||||
using Lumina.Excel.Sheets;
|
using Lumina.Excel.Sheets;
|
||||||
using LightlessSync.UI.Services;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using LightlessSync.UI;
|
|
||||||
using LightlessSync.Services.LightFinder;
|
|
||||||
|
|
||||||
namespace LightlessSync.Services;
|
namespace LightlessSync.Services;
|
||||||
|
|
||||||
internal class ContextMenuService : IHostedService
|
internal class ContextMenuService : IHostedService
|
||||||
{
|
{
|
||||||
private readonly IContextMenu _contextMenu;
|
private readonly IContextMenu _contextMenu;
|
||||||
|
private readonly IChatGui _chatGui;
|
||||||
private readonly IDalamudPluginInterface _pluginInterface;
|
private readonly IDalamudPluginInterface _pluginInterface;
|
||||||
private readonly IDataManager _gameData;
|
private readonly IDataManager _gameData;
|
||||||
private readonly ILogger<ContextMenuService> _logger;
|
private readonly ILogger<ContextMenuService> _logger;
|
||||||
@@ -29,6 +30,7 @@ internal class ContextMenuService : IHostedService
|
|||||||
private readonly ApiController _apiController;
|
private readonly ApiController _apiController;
|
||||||
private readonly IObjectTable _objectTable;
|
private readonly IObjectTable _objectTable;
|
||||||
private readonly LightlessConfigService _configService;
|
private readonly LightlessConfigService _configService;
|
||||||
|
private readonly NotificationService _lightlessNotification;
|
||||||
private readonly LightFinderScannerService _broadcastScannerService;
|
private readonly LightFinderScannerService _broadcastScannerService;
|
||||||
private readonly LightFinderService _broadcastService;
|
private readonly LightFinderService _broadcastService;
|
||||||
private readonly LightlessProfileManager _lightlessProfileManager;
|
private readonly LightlessProfileManager _lightlessProfileManager;
|
||||||
@@ -51,7 +53,9 @@ internal class ContextMenuService : IHostedService
|
|||||||
LightFinderScannerService broadcastScannerService,
|
LightFinderScannerService broadcastScannerService,
|
||||||
LightFinderService broadcastService,
|
LightFinderService broadcastService,
|
||||||
LightlessProfileManager lightlessProfileManager,
|
LightlessProfileManager lightlessProfileManager,
|
||||||
LightlessMediator mediator)
|
LightlessMediator mediator,
|
||||||
|
IChatGui chatGui,
|
||||||
|
NotificationService lightlessNotification)
|
||||||
{
|
{
|
||||||
_contextMenu = contextMenu;
|
_contextMenu = contextMenu;
|
||||||
_pluginInterface = pluginInterface;
|
_pluginInterface = pluginInterface;
|
||||||
@@ -68,6 +72,8 @@ internal class ContextMenuService : IHostedService
|
|||||||
_broadcastService = broadcastService;
|
_broadcastService = broadcastService;
|
||||||
_lightlessProfileManager = lightlessProfileManager;
|
_lightlessProfileManager = lightlessProfileManager;
|
||||||
_mediator = mediator;
|
_mediator = mediator;
|
||||||
|
_chatGui = chatGui;
|
||||||
|
_lightlessNotification = lightlessNotification;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task StartAsync(CancellationToken cancellationToken)
|
public Task StartAsync(CancellationToken cancellationToken)
|
||||||
@@ -99,6 +105,12 @@ internal class ContextMenuService : IHostedService
|
|||||||
if (!_pluginInterface.UiBuilder.ShouldModifyUi)
|
if (!_pluginInterface.UiBuilder.ShouldModifyUi)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
if (!_configService.Current.EnableRightClickMenus)
|
||||||
|
{
|
||||||
|
_logger.LogTrace("Right-click menus are disabled in configuration.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (args.AddonName != null)
|
if (args.AddonName != null)
|
||||||
{
|
{
|
||||||
var addonName = args.AddonName;
|
var addonName = args.AddonName;
|
||||||
@@ -198,6 +210,18 @@ internal class ContextMenuService : IHostedService
|
|||||||
.Where(p => p.IsVisible && p.PlayerCharacterId != uint.MaxValue)
|
.Where(p => p.IsVisible && p.PlayerCharacterId != uint.MaxValue)
|
||||||
.Select(p => (ulong)p.PlayerCharacterId)];
|
.Select(p => (ulong)p.PlayerCharacterId)];
|
||||||
|
|
||||||
|
private void NotifyInChat(string message, NotificationType type = NotificationType.Info)
|
||||||
|
{
|
||||||
|
if (!_configService.Current.UseLightlessNotifications || (_configService.Current.LightlessPairRequestNotification == NotificationLocation.Chat || _configService.Current.LightlessPairRequestNotification == NotificationLocation.ChatAndLightlessUi))
|
||||||
|
{
|
||||||
|
var chatMsg = $"[Lightless] {message}";
|
||||||
|
if (type == NotificationType.Error)
|
||||||
|
_chatGui.PrintError(chatMsg);
|
||||||
|
else
|
||||||
|
_chatGui.Print(chatMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async Task HandleSelection(IMenuArgs args)
|
private async Task HandleSelection(IMenuArgs args)
|
||||||
{
|
{
|
||||||
if (args.Target is not MenuTargetDefault target)
|
if (args.Target is not MenuTargetDefault target)
|
||||||
@@ -226,6 +250,9 @@ internal class ContextMenuService : IHostedService
|
|||||||
{
|
{
|
||||||
_pairRequestService.RemoveRequest(receiverCid);
|
_pairRequestService.RemoveRequest(receiverCid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Notify in chat when NotificationService is disabled
|
||||||
|
NotifyInChat($"Pair request sent to {target.TargetName}@{world.Name}.", NotificationType.Info);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
|||||||
71
LightlessSync/Services/PenumbraTempCollectionJanitor.cs
Normal file
71
LightlessSync/Services/PenumbraTempCollectionJanitor.cs
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
using LightlessSync.Interop.Ipc;
|
||||||
|
using LightlessSync.LightlessConfiguration;
|
||||||
|
using LightlessSync.Services.Mediator;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace LightlessSync.Services;
|
||||||
|
|
||||||
|
public sealed class PenumbraTempCollectionJanitor : DisposableMediatorSubscriberBase
|
||||||
|
{
|
||||||
|
private readonly IpcManager _ipc;
|
||||||
|
private readonly LightlessConfigService _config;
|
||||||
|
private int _ran;
|
||||||
|
|
||||||
|
public PenumbraTempCollectionJanitor(
|
||||||
|
ILogger<PenumbraTempCollectionJanitor> logger,
|
||||||
|
LightlessMediator mediator,
|
||||||
|
IpcManager ipc,
|
||||||
|
LightlessConfigService config) : base(logger, mediator)
|
||||||
|
{
|
||||||
|
_ipc = ipc;
|
||||||
|
_config = config;
|
||||||
|
|
||||||
|
Mediator.Subscribe<PenumbraInitializedMessage>(this, _ => CleanupOrphansOnBoot());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Register(Guid id)
|
||||||
|
{
|
||||||
|
if (id == Guid.Empty) return;
|
||||||
|
if (_config.Current.OrphanableTempCollections.Add(id))
|
||||||
|
_config.Save();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Unregister(Guid id)
|
||||||
|
{
|
||||||
|
if (id == Guid.Empty) return;
|
||||||
|
if (_config.Current.OrphanableTempCollections.Remove(id))
|
||||||
|
_config.Save();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CleanupOrphansOnBoot()
|
||||||
|
{
|
||||||
|
if (Interlocked.Exchange(ref _ran, 1) == 1)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (!_ipc.Penumbra.APIAvailable)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var ids = _config.Current.OrphanableTempCollections.ToArray();
|
||||||
|
if (ids.Length == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var appId = Guid.NewGuid();
|
||||||
|
Logger.LogInformation("Cleaning up {count} orphaned Lightless temp collections found in configuration", ids.Length);
|
||||||
|
|
||||||
|
foreach (var id in ids)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_ipc.Penumbra.RemoveTemporaryCollectionAsync(Logger, appId, id)
|
||||||
|
.GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Logger.LogDebug(ex, "Failed removing orphaned temp collection {id}", id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_config.Current.OrphanableTempCollections.Clear();
|
||||||
|
_config.Save();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -178,6 +178,11 @@ public class DownloadUi : WindowMediatorSubscriberBase
|
|||||||
foreach (var transfer in transfers)
|
foreach (var transfer in transfers)
|
||||||
{
|
{
|
||||||
var transferKey = transfer.Key;
|
var transferKey = transfer.Key;
|
||||||
|
|
||||||
|
// Skip if no valid game object
|
||||||
|
if (transferKey.GetGameObject() == null)
|
||||||
|
continue;
|
||||||
|
|
||||||
var rawPos = _dalamudUtilService.WorldToScreen(transferKey.GetGameObject());
|
var rawPos = _dalamudUtilService.WorldToScreen(transferKey.GetGameObject());
|
||||||
|
|
||||||
// If RawPos is zero, remove it from smoothed dictionary
|
// If RawPos is zero, remove it from smoothed dictionary
|
||||||
|
|||||||
@@ -781,7 +781,8 @@ public class TopTabMenu
|
|||||||
{
|
{
|
||||||
var buttonX = (availableWidth - (spacingX)) / 2f;
|
var buttonX = (availableWidth - (spacingX)) / 2f;
|
||||||
|
|
||||||
if (_uiSharedService.IconTextButton(FontAwesomeIcon.PersonCirclePlus, "Lightfinder", buttonX, center: true))
|
var lightFinderLabel = GetLightfinderFinderLabel();
|
||||||
|
if (_uiSharedService.IconTextButton(FontAwesomeIcon.PersonCirclePlus, lightFinderLabel, buttonX, center: true))
|
||||||
{
|
{
|
||||||
_lightlessMediator.Publish(new UiToggleMessage(typeof(LightFinderUI)));
|
_lightlessMediator.Publish(new UiToggleMessage(typeof(LightFinderUI)));
|
||||||
}
|
}
|
||||||
@@ -795,6 +796,20 @@ public class TopTabMenu
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private string GetLightfinderFinderLabel()
|
||||||
|
{
|
||||||
|
string label = "Lightfinder";
|
||||||
|
|
||||||
|
if (_lightFinderService.IsBroadcasting)
|
||||||
|
{
|
||||||
|
var hashExclude = _dalamudUtilService.GetCID().ToString().GetHash256();
|
||||||
|
var nearbyCount = _lightFinderScannerService.GetActiveBroadcasts(hashExclude).Count;
|
||||||
|
return $"{label} ({nearbyCount})";
|
||||||
|
}
|
||||||
|
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
private string GetSyncshellFinderLabel()
|
private string GetSyncshellFinderLabel()
|
||||||
{
|
{
|
||||||
if (!_lightFinderService.IsBroadcasting)
|
if (!_lightFinderService.IsBroadcasting)
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -18,56 +18,72 @@ public class FileTransferOrchestrator : DisposableMediatorSubscriberBase
|
|||||||
private readonly LightlessConfigService _lightlessConfig;
|
private readonly LightlessConfigService _lightlessConfig;
|
||||||
private readonly object _semaphoreModificationLock = new();
|
private readonly object _semaphoreModificationLock = new();
|
||||||
private readonly TokenProvider _tokenProvider;
|
private readonly TokenProvider _tokenProvider;
|
||||||
|
|
||||||
private int _availableDownloadSlots;
|
private int _availableDownloadSlots;
|
||||||
private SemaphoreSlim _downloadSemaphore;
|
private SemaphoreSlim _downloadSemaphore;
|
||||||
|
|
||||||
private int CurrentlyUsedDownloadSlots => _availableDownloadSlots - _downloadSemaphore.CurrentCount;
|
private int CurrentlyUsedDownloadSlots => _availableDownloadSlots - _downloadSemaphore.CurrentCount;
|
||||||
|
|
||||||
public FileTransferOrchestrator(ILogger<FileTransferOrchestrator> logger, LightlessConfigService lightlessConfig,
|
public FileTransferOrchestrator(
|
||||||
LightlessMediator mediator, TokenProvider tokenProvider, HttpClient httpClient) : base(logger, mediator)
|
ILogger<FileTransferOrchestrator> logger,
|
||||||
|
LightlessConfigService lightlessConfig,
|
||||||
|
LightlessMediator mediator,
|
||||||
|
TokenProvider tokenProvider,
|
||||||
|
HttpClient httpClient) : base(logger, mediator)
|
||||||
{
|
{
|
||||||
_lightlessConfig = lightlessConfig;
|
_lightlessConfig = lightlessConfig;
|
||||||
_tokenProvider = tokenProvider;
|
_tokenProvider = tokenProvider;
|
||||||
_httpClient = httpClient;
|
_httpClient = httpClient;
|
||||||
|
|
||||||
var ver = Assembly.GetExecutingAssembly().GetName().Version;
|
var ver = Assembly.GetExecutingAssembly().GetName().Version;
|
||||||
_httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("LightlessSync", ver!.Major + "." + ver!.Minor + "." + ver!.Build));
|
_httpClient.DefaultRequestHeaders.UserAgent.Add(
|
||||||
|
new ProductInfoHeaderValue("LightlessSync", $"{ver!.Major}.{ver.Minor}.{ver.Build}"));
|
||||||
|
|
||||||
_availableDownloadSlots = lightlessConfig.Current.ParallelDownloads;
|
_availableDownloadSlots = Math.Max(1, lightlessConfig.Current.ParallelDownloads);
|
||||||
_downloadSemaphore = new(_availableDownloadSlots, _availableDownloadSlots);
|
_downloadSemaphore = new SemaphoreSlim(_availableDownloadSlots, _availableDownloadSlots);
|
||||||
|
|
||||||
Mediator.Subscribe<ConnectedMessage>(this, (msg) =>
|
Mediator.Subscribe<ConnectedMessage>(this, msg => FilesCdnUri = msg.Connection.ServerInfo.FileServerAddress);
|
||||||
{
|
Mediator.Subscribe<DisconnectedMessage>(this, _ => FilesCdnUri = null);
|
||||||
FilesCdnUri = msg.Connection.ServerInfo.FileServerAddress;
|
Mediator.Subscribe<DownloadReadyMessage>(this, msg => _downloadReady[msg.RequestId] = true);
|
||||||
});
|
|
||||||
|
|
||||||
Mediator.Subscribe<DisconnectedMessage>(this, (msg) =>
|
|
||||||
{
|
|
||||||
FilesCdnUri = null;
|
|
||||||
});
|
|
||||||
Mediator.Subscribe<DownloadReadyMessage>(this, (msg) =>
|
|
||||||
{
|
|
||||||
_downloadReady[msg.RequestId] = true;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Files CDN Uri from server
|
||||||
|
/// </summary>
|
||||||
public Uri? FilesCdnUri { private set; get; }
|
public Uri? FilesCdnUri { private set; get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Forbidden file transfers given by server
|
||||||
|
/// </summary>
|
||||||
public List<FileTransfer> ForbiddenTransfers { get; } = [];
|
public List<FileTransfer> ForbiddenTransfers { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Is the FileTransferOrchestrator initialized
|
||||||
|
/// </summary>
|
||||||
public bool IsInitialized => FilesCdnUri != null;
|
public bool IsInitialized => FilesCdnUri != null;
|
||||||
|
|
||||||
public void ClearDownloadRequest(Guid guid)
|
/// <summary>
|
||||||
{
|
/// Configured parallel downloads in settings (ParallelDownloads)
|
||||||
_downloadReady.Remove(guid, out _);
|
/// </summary>
|
||||||
}
|
public int ConfiguredParallelDownloads => Math.Max(1, _lightlessConfig.Current.ParallelDownloads);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Clears the download request for the given guid
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="guid">Guid of download request</param>
|
||||||
|
public void ClearDownloadRequest(Guid guid) => _downloadReady.Remove(guid, out _);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Is the download ready for the given guid
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="guid">Guid of download request</param>
|
||||||
|
/// <returns>Completion of the download</returns>
|
||||||
public bool IsDownloadReady(Guid guid)
|
public bool IsDownloadReady(Guid guid)
|
||||||
{
|
=> _downloadReady.TryGetValue(guid, out bool isReady) && isReady;
|
||||||
if (_downloadReady.TryGetValue(guid, out bool isReady) && isReady)
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Release a download slot after download is complete
|
||||||
|
/// </summary>
|
||||||
public void ReleaseDownloadSlot()
|
public void ReleaseDownloadSlot()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@@ -81,60 +97,26 @@ public class FileTransferOrchestrator : DisposableMediatorSubscriberBase
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<HttpResponseMessage> SendRequestAsync(HttpMethod method, Uri uri,
|
/// <summary>
|
||||||
CancellationToken? ct = null, HttpCompletionOption httpCompletionOption = HttpCompletionOption.ResponseContentRead,
|
/// Wait for an available download slot asyncronously
|
||||||
bool withToken = true)
|
/// </summary>
|
||||||
{
|
/// <param name="token">Cancellation Token</param>
|
||||||
return await SendRequestInternalAsync(() => new HttpRequestMessage(method, uri),
|
/// <returns>Task of the slot</returns>
|
||||||
ct, httpCompletionOption, withToken, allowRetry: true).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<HttpResponseMessage> SendRequestAsync<T>(HttpMethod method, Uri uri, T content, CancellationToken ct,
|
|
||||||
bool withToken = true) where T : class
|
|
||||||
{
|
|
||||||
return await SendRequestInternalAsync(() =>
|
|
||||||
{
|
|
||||||
var requestMessage = new HttpRequestMessage(method, uri);
|
|
||||||
if (content is not ByteArrayContent byteArrayContent)
|
|
||||||
{
|
|
||||||
requestMessage.Content = JsonContent.Create(content);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
var clonedContent = new ByteArrayContent(byteArrayContent.ReadAsByteArrayAsync().GetAwaiter().GetResult());
|
|
||||||
foreach (var header in byteArrayContent.Headers)
|
|
||||||
{
|
|
||||||
clonedContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
|
|
||||||
}
|
|
||||||
requestMessage.Content = clonedContent;
|
|
||||||
}
|
|
||||||
|
|
||||||
return requestMessage;
|
|
||||||
}, ct, HttpCompletionOption.ResponseContentRead, withToken,
|
|
||||||
allowRetry: content is not HttpContent || content is ByteArrayContent).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<HttpResponseMessage> SendRequestStreamAsync(HttpMethod method, Uri uri, ProgressableStreamContent content,
|
|
||||||
CancellationToken ct, bool withToken = true)
|
|
||||||
{
|
|
||||||
return await SendRequestInternalAsync(() =>
|
|
||||||
{
|
|
||||||
var requestMessage = new HttpRequestMessage(method, uri)
|
|
||||||
{
|
|
||||||
Content = content
|
|
||||||
};
|
|
||||||
return requestMessage;
|
|
||||||
}, ct, HttpCompletionOption.ResponseContentRead, withToken, allowRetry: false).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task WaitForDownloadSlotAsync(CancellationToken token)
|
public async Task WaitForDownloadSlotAsync(CancellationToken token)
|
||||||
{
|
{
|
||||||
lock (_semaphoreModificationLock)
|
lock (_semaphoreModificationLock)
|
||||||
{
|
{
|
||||||
if (_availableDownloadSlots != _lightlessConfig.Current.ParallelDownloads && _availableDownloadSlots == _downloadSemaphore.CurrentCount)
|
var desired = Math.Max(1, _lightlessConfig.Current.ParallelDownloads);
|
||||||
|
|
||||||
|
if (_availableDownloadSlots != desired &&
|
||||||
|
_availableDownloadSlots == _downloadSemaphore.CurrentCount)
|
||||||
{
|
{
|
||||||
_availableDownloadSlots = _lightlessConfig.Current.ParallelDownloads;
|
_availableDownloadSlots = desired;
|
||||||
_downloadSemaphore = new(_availableDownloadSlots, _availableDownloadSlots);
|
|
||||||
|
var old = _downloadSemaphore;
|
||||||
|
_downloadSemaphore = new SemaphoreSlim(_availableDownloadSlots, _availableDownloadSlots);
|
||||||
|
|
||||||
|
try { old.Dispose(); } catch { /* ignore */ }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,10 +124,15 @@ public class FileTransferOrchestrator : DisposableMediatorSubscriberBase
|
|||||||
Mediator.Publish(new DownloadLimitChangedMessage());
|
Mediator.Publish(new DownloadLimitChangedMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Download limit per slot in bytes
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>Bytes of the download limit</returns>
|
||||||
public long DownloadLimitPerSlot()
|
public long DownloadLimitPerSlot()
|
||||||
{
|
{
|
||||||
var limit = _lightlessConfig.Current.DownloadSpeedLimitInBytes;
|
var limit = _lightlessConfig.Current.DownloadSpeedLimitInBytes;
|
||||||
if (limit <= 0) return 0;
|
if (limit <= 0) return 0;
|
||||||
|
|
||||||
limit = _lightlessConfig.Current.DownloadSpeedType switch
|
limit = _lightlessConfig.Current.DownloadSpeedType switch
|
||||||
{
|
{
|
||||||
LightlessConfiguration.Models.DownloadSpeeds.Bps => limit,
|
LightlessConfiguration.Models.DownloadSpeeds.Bps => limit,
|
||||||
@@ -153,22 +140,113 @@ public class FileTransferOrchestrator : DisposableMediatorSubscriberBase
|
|||||||
LightlessConfiguration.Models.DownloadSpeeds.MBps => limit * 1024 * 1024,
|
LightlessConfiguration.Models.DownloadSpeeds.MBps => limit * 1024 * 1024,
|
||||||
_ => limit,
|
_ => limit,
|
||||||
};
|
};
|
||||||
var currentUsedDlSlots = CurrentlyUsedDownloadSlots;
|
|
||||||
var avaialble = _availableDownloadSlots;
|
var usedSlots = CurrentlyUsedDownloadSlots;
|
||||||
var currentCount = _downloadSemaphore.CurrentCount;
|
var divided = limit / (usedSlots <= 0 ? 1 : usedSlots);
|
||||||
var dividedLimit = limit / (currentUsedDlSlots == 0 ? 1 : currentUsedDlSlots);
|
|
||||||
if (dividedLimit < 0)
|
if (divided < 0)
|
||||||
{
|
{
|
||||||
Logger.LogWarning("Calculated Bandwidth Limit is negative, returning Infinity: {value}, CurrentlyUsedDownloadSlots is {currentSlots}, " +
|
Logger.LogWarning(
|
||||||
"DownloadSpeedLimit is {limit}, available slots: {avail}, current count: {count}", dividedLimit, currentUsedDlSlots, limit, avaialble, currentCount);
|
"Calculated Bandwidth Limit is negative, returning Infinity: {value}, usedSlots={usedSlots}, limit={limit}, avail={avail}, currentCount={count}",
|
||||||
|
divided, usedSlots, limit, _availableDownloadSlots, _downloadSemaphore.CurrentCount);
|
||||||
return long.MaxValue;
|
return long.MaxValue;
|
||||||
}
|
}
|
||||||
return Math.Clamp(dividedLimit, 1, long.MaxValue);
|
|
||||||
|
return Math.Clamp(divided, 1, long.MaxValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<HttpResponseMessage> SendRequestInternalAsync(Func<HttpRequestMessage> requestFactory,
|
/// <summary>
|
||||||
CancellationToken? ct = null, HttpCompletionOption httpCompletionOption = HttpCompletionOption.ResponseContentRead,
|
/// sends an HTTP request without content serialization
|
||||||
bool withToken = true, bool allowRetry = true)
|
/// </summary>
|
||||||
|
/// <param name="method">HttpMethod for the request</param>
|
||||||
|
/// <param name="uri">Uri for the request</param>
|
||||||
|
/// <param name="ct">Cancellation Token</param>
|
||||||
|
/// <param name="httpCompletionOption">Enum of HttpCollectionOption</param>
|
||||||
|
/// <param name="withToken">Include Cancellation Token</param>
|
||||||
|
/// <returns>Http response of the request</returns>
|
||||||
|
public async Task<HttpResponseMessage> SendRequestAsync(
|
||||||
|
HttpMethod method,
|
||||||
|
Uri uri,
|
||||||
|
CancellationToken? ct = null,
|
||||||
|
HttpCompletionOption httpCompletionOption = HttpCompletionOption.ResponseContentRead,
|
||||||
|
bool withToken = true)
|
||||||
|
{
|
||||||
|
return await SendRequestInternalAsync(
|
||||||
|
() => new HttpRequestMessage(method, uri),
|
||||||
|
ct,
|
||||||
|
httpCompletionOption,
|
||||||
|
withToken,
|
||||||
|
allowRetry: true).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sends an HTTP request with JSON content serialization
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">HttpResponseMessage</typeparam>
|
||||||
|
/// <param name="method">Http method</param>
|
||||||
|
/// <param name="uri">Url of the direct download link</param>
|
||||||
|
/// <param name="content">content of the request</param>
|
||||||
|
/// <param name="ct">cancellation token</param>
|
||||||
|
/// <param name="withToken">include cancellation token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<HttpResponseMessage> SendRequestAsync<T>(
|
||||||
|
HttpMethod method,
|
||||||
|
Uri uri,
|
||||||
|
T content,
|
||||||
|
CancellationToken ct,
|
||||||
|
bool withToken = true) where T : class
|
||||||
|
{
|
||||||
|
return await SendRequestInternalAsync(() =>
|
||||||
|
{
|
||||||
|
var requestMessage = new HttpRequestMessage(method, uri);
|
||||||
|
|
||||||
|
if (content is ByteArrayContent byteArrayContent)
|
||||||
|
{
|
||||||
|
var bytes = byteArrayContent.ReadAsByteArrayAsync(ct).GetAwaiter().GetResult();
|
||||||
|
var cloned = new ByteArrayContent(bytes);
|
||||||
|
foreach (var header in byteArrayContent.Headers)
|
||||||
|
cloned.Headers.TryAddWithoutValidation(header.Key, header.Value);
|
||||||
|
|
||||||
|
requestMessage.Content = cloned;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
requestMessage.Content = JsonContent.Create(content);
|
||||||
|
}
|
||||||
|
|
||||||
|
return requestMessage;
|
||||||
|
}, ct, HttpCompletionOption.ResponseContentRead, withToken,
|
||||||
|
allowRetry: content is not HttpContent || content is ByteArrayContent).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<HttpResponseMessage> SendRequestStreamAsync(
|
||||||
|
HttpMethod method,
|
||||||
|
Uri uri,
|
||||||
|
ProgressableStreamContent content,
|
||||||
|
CancellationToken ct,
|
||||||
|
bool withToken = true)
|
||||||
|
{
|
||||||
|
return await SendRequestInternalAsync(() =>
|
||||||
|
{
|
||||||
|
return new HttpRequestMessage(method, uri) { Content = content };
|
||||||
|
}, ct, HttpCompletionOption.ResponseContentRead, withToken, allowRetry: false).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// sends an HTTP request with optional retry logic for transient network errors
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="requestFactory">Request factory</param>
|
||||||
|
/// <param name="ct">Cancellation Token</param>
|
||||||
|
/// <param name="httpCompletionOption">Http Options</param>
|
||||||
|
/// <param name="withToken">With cancellation token</param>
|
||||||
|
/// <param name="allowRetry">Allows retry of request</param>
|
||||||
|
/// <returns>Response message of request</returns>
|
||||||
|
private async Task<HttpResponseMessage> SendRequestInternalAsync(
|
||||||
|
Func<HttpRequestMessage> requestFactory,
|
||||||
|
CancellationToken? ct = null,
|
||||||
|
HttpCompletionOption httpCompletionOption = HttpCompletionOption.ResponseContentRead,
|
||||||
|
bool withToken = true,
|
||||||
|
bool allowRetry = true)
|
||||||
{
|
{
|
||||||
const int maxAttempts = 2;
|
const int maxAttempts = 2;
|
||||||
var attempt = 0;
|
var attempt = 0;
|
||||||
@@ -184,8 +262,11 @@ public class FileTransferOrchestrator : DisposableMediatorSubscriberBase
|
|||||||
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (requestMessage.Content != null && requestMessage.Content is not StreamContent && requestMessage.Content is not ByteArrayContent)
|
if (requestMessage.Content != null &&
|
||||||
|
requestMessage.Content is not StreamContent &&
|
||||||
|
requestMessage.Content is not ByteArrayContent)
|
||||||
{
|
{
|
||||||
|
// log content for debugging
|
||||||
var content = await ((JsonContent)requestMessage.Content).ReadAsStringAsync().ConfigureAwait(false);
|
var content = await ((JsonContent)requestMessage.Content).ReadAsStringAsync().ConfigureAwait(false);
|
||||||
Logger.LogDebug("Sending {method} to {uri} (Content: {content})", requestMessage.Method, requestMessage.RequestUri, content);
|
Logger.LogDebug("Sending {method} to {uri} (Content: {content})", requestMessage.Method, requestMessage.RequestUri, content);
|
||||||
}
|
}
|
||||||
@@ -196,9 +277,10 @@ public class FileTransferOrchestrator : DisposableMediatorSubscriberBase
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (ct != null)
|
// send request
|
||||||
return await _httpClient.SendAsync(requestMessage, httpCompletionOption, ct.Value).ConfigureAwait(false);
|
return ct != null
|
||||||
return await _httpClient.SendAsync(requestMessage, httpCompletionOption).ConfigureAwait(false);
|
? await _httpClient.SendAsync(requestMessage, httpCompletionOption, ct.Value).ConfigureAwait(false)
|
||||||
|
: await _httpClient.SendAsync(requestMessage, httpCompletionOption).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (TaskCanceledException)
|
catch (TaskCanceledException)
|
||||||
{
|
{
|
||||||
@@ -208,14 +290,11 @@ public class FileTransferOrchestrator : DisposableMediatorSubscriberBase
|
|||||||
{
|
{
|
||||||
Logger.LogWarning(ex, "Transient error during SendRequestInternal for {uri}, retrying attempt {attempt}/{maxAttempts}",
|
Logger.LogWarning(ex, "Transient error during SendRequestInternal for {uri}, retrying attempt {attempt}/{maxAttempts}",
|
||||||
requestMessage.RequestUri, attempt, maxAttempts);
|
requestMessage.RequestUri, attempt, maxAttempts);
|
||||||
|
|
||||||
if (ct.HasValue)
|
if (ct.HasValue)
|
||||||
{
|
|
||||||
await Task.Delay(TimeSpan.FromMilliseconds(200), ct.Value).ConfigureAwait(false);
|
await Task.Delay(TimeSpan.FromMilliseconds(200), ct.Value).ConfigureAwait(false);
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
|
||||||
await Task.Delay(TimeSpan.FromMilliseconds(200)).ConfigureAwait(false);
|
await Task.Delay(TimeSpan.FromMilliseconds(200)).ConfigureAwait(false);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -225,6 +304,11 @@ public class FileTransferOrchestrator : DisposableMediatorSubscriberBase
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Is the exception a transient network exception
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="ex">expection</param>
|
||||||
|
/// <returns>Is transient network expection</returns>
|
||||||
private static bool IsTransientNetworkException(Exception ex)
|
private static bool IsTransientNetworkException(Exception ex)
|
||||||
{
|
{
|
||||||
var current = ex;
|
var current = ex;
|
||||||
@@ -232,12 +316,13 @@ public class FileTransferOrchestrator : DisposableMediatorSubscriberBase
|
|||||||
{
|
{
|
||||||
if (current is SocketException socketEx)
|
if (current is SocketException socketEx)
|
||||||
{
|
{
|
||||||
return socketEx.SocketErrorCode is SocketError.ConnectionReset or SocketError.ConnectionAborted or SocketError.TimedOut;
|
return socketEx.SocketErrorCode is
|
||||||
|
SocketError.ConnectionReset or
|
||||||
|
SocketError.ConnectionAborted or
|
||||||
|
SocketError.TimedOut;
|
||||||
}
|
}
|
||||||
|
|
||||||
current = current.InnerException;
|
current = current.InnerException;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user