Some checks failed
Tag and Release Lightless / tag-and-release (push) Failing after 32s
 Lightless 1.12.0 is HERE! In this major update, we are introducing something we've been working on and testing for the last couple of weeks. In this update we are introducing a new (**OPTIONAL**) feature called **LightFinder**! We took inspiration from FFXIV's very own Party Finder and decided to implement something that allows users to not only look for fellow Lightless users, but also put up their Syncshell for others looking to join a sync community! When you enable LightFinder, you will be visible to other LightFinder users for **3 hours** or when you want to disabled it. When the 3 hours are up, you can either leave it disabled or enable it again for another 3 hours. The tag shown above will show above your nameplate, and you will be able to receive pair requests in your UI from other users with LightFinder enabled without having to input their uid!  Are you at a Venue? In Limsa? Partying in the streets of Uldah? If you're looking for fellow Lightless users you can now enable LightFinder and you will be shown to others who also have LightFinder enabled! Looking for a Syncshell to join? Enable LightFinder to see what SyncShells are available to join! Want to advertise your Syncshell? Choose the syncshell you want to put up in LightFinder and enable LightFinder. **IMPORTANT: We want to stress the fact that, if you just want to sync with just your friends and no one else, this does not take that away. No one will know you use Lightless unless you choose to tell them, or use this **OPTIONAL** feature. Your privacy is still maintained if you don't want to use the feature.** # Major Changes ## LightFinder - **OPTIONAL FEATURE** - **DOES NOT AFFECT YOU IF YOU DON'T WANT TO USE IT**  * New **OPTIONAL** syncing feature where one can enable something like a Party Finder so that other Lightless users in the area can see you are looking for people to sync with. Enable it by clicking the compass button and then the `Enable LightFinder` button.  * [L] Send Pair Request has been added to player context menus. You should still be able to send a request without Lightfinder on BUT you will need to know the other player is using Lightless and have them send a pair request back.  * When in LightFinder mode, for X mins you will be visible to all Lightless Users WHO ALSO HAVE LIGHTFINDER ON and will receive notifications of people wanting to pair with you. If you are the person using LightFinder, you understand the risks of pairing with someone you don't know. If you are the person sending a request to someone with LightFinder on, you also understand the risks of pairing with someone you don't know. **AGAIN, THIS IS OPTIONAL.** * When in LightFinder mode, you can also put up a Syncshell you own on the Syncshell Finder so that others can easily find it and join. This has to be done prior to enabling LightFinder.  * Syncshell Finder allows you to join Syncshells that are indexed by LightFinder  # Minor Changes * Vanity addition to our supporters: On top of vanity ids you can find a fun addition under Your User Settings -> Edit Lightless Profile -> Vanity Settings to change the colour of your name in the lightless ui. This will be shown to all users.  * Pairing nameplate colour override can also now override FC tag (new option_ * Bunch of UI fixes, updates, and changes * kdb is now a whitelisted filetype that can upload Co-authored-by: CakeAndBanana <admin@cakeandbanana.nl> Co-authored-by: azyges <aaaaaa@aaa.aaa> Co-authored-by: choco <thijmenhogenkamp@gmail.com> Co-authored-by: choco <choco@noreply.git.lightless-sync.org> Co-authored-by: defnotken <itsdefnotken@gmail.com> Reviewed-on: #39
377 lines
14 KiB
C#
377 lines
14 KiB
C#
using LightlessSync.API.Dto.Group;
|
|
using LightlessSync.API.Dto.User;
|
|
using LightlessSync.LightlessConfiguration;
|
|
using LightlessSync.Services.Mediator;
|
|
using LightlessSync.Utils;
|
|
using LightlessSync.WebAPI;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace LightlessSync.Services;
|
|
public class BroadcastService : IHostedService, IMediatorSubscriber
|
|
{
|
|
private readonly ILogger<BroadcastService> _logger;
|
|
private readonly ApiController _apiController;
|
|
private readonly LightlessMediator _mediator;
|
|
private readonly LightlessConfigService _config;
|
|
private readonly DalamudUtilService _dalamudUtil;
|
|
public LightlessMediator Mediator => _mediator;
|
|
|
|
public bool IsLightFinderAvailable { get; private set; } = true;
|
|
|
|
public bool IsBroadcasting => _config.Current.BroadcastEnabled;
|
|
private bool _syncedOnStartup = false;
|
|
private bool _waitingForTtlFetch = false;
|
|
private TimeSpan? _remainingTtl = null;
|
|
private DateTime _lastTtlCheck = DateTime.MinValue;
|
|
private DateTime _lastForcedDisableTime = DateTime.MinValue;
|
|
private static readonly TimeSpan _disableCooldown = TimeSpan.FromSeconds(5);
|
|
public TimeSpan? RemainingTtl => _remainingTtl;
|
|
public TimeSpan? RemainingCooldown
|
|
{
|
|
get
|
|
{
|
|
var elapsed = DateTime.UtcNow - _lastForcedDisableTime;
|
|
if (elapsed >= _disableCooldown) return null;
|
|
return _disableCooldown - elapsed;
|
|
}
|
|
}
|
|
|
|
public BroadcastService(ILogger<BroadcastService> logger, LightlessMediator mediator, LightlessConfigService config, DalamudUtilService dalamudUtil, ApiController apiController)
|
|
{
|
|
_logger = logger;
|
|
_mediator = mediator;
|
|
_config = config;
|
|
_dalamudUtil = dalamudUtil;
|
|
_apiController = apiController;
|
|
}
|
|
|
|
private async Task RequireConnectionAsync(string context, Func<Task> action)
|
|
{
|
|
if (!_apiController.IsConnected)
|
|
{
|
|
_logger.LogDebug(context + " skipped, not connected");
|
|
return;
|
|
}
|
|
await action().ConfigureAwait(false);
|
|
}
|
|
|
|
public async Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
_mediator.Subscribe<EnableBroadcastMessage>(this, OnEnableBroadcast);
|
|
_mediator.Subscribe<BroadcastStatusChangedMessage>(this, OnBroadcastStatusChanged);
|
|
_mediator.Subscribe<PriorityFrameworkUpdateMessage>(this, OnTick);
|
|
|
|
_apiController.OnConnected += () => _ = CheckLightfinderSupportAsync(cancellationToken);
|
|
//_ = CheckLightfinderSupportAsync(cancellationToken);
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
_mediator.UnsubscribeAll(this);
|
|
_apiController.OnConnected -= () => _ = CheckLightfinderSupportAsync(cancellationToken);
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
// need to rework this, this is cooked
|
|
private async Task CheckLightfinderSupportAsync(CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
while (!_apiController.IsConnected && !cancellationToken.IsCancellationRequested)
|
|
await Task.Delay(250, cancellationToken).ConfigureAwait(false);
|
|
|
|
if (cancellationToken.IsCancellationRequested)
|
|
return;
|
|
|
|
var dummy = "0".PadLeft(64, '0');
|
|
|
|
await _apiController.IsUserBroadcasting(dummy).ConfigureAwait(false);
|
|
await _apiController.SetBroadcastStatus(dummy, true, null).ConfigureAwait(false);
|
|
await _apiController.GetBroadcastTtl(dummy).ConfigureAwait(false);
|
|
await _apiController.AreUsersBroadcasting([dummy]).ConfigureAwait(false);
|
|
|
|
IsLightFinderAvailable = true;
|
|
_logger.LogInformation("Lightfinder is available.");
|
|
}
|
|
catch (HubException ex) when (ex.Message.Contains("Method does not exist"))
|
|
{
|
|
_logger.LogWarning("Lightfinder unavailable: required method missing.");
|
|
IsLightFinderAvailable = false;
|
|
|
|
_config.Current.BroadcastEnabled = false;
|
|
_config.Current.BroadcastTtl = DateTime.MinValue;
|
|
_config.Save();
|
|
_mediator.Publish(new BroadcastStatusChangedMessage(false, null));
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
_logger.LogInformation("Lightfinder check was canceled.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Lightfinder check failed.");
|
|
IsLightFinderAvailable = false;
|
|
|
|
_config.Current.BroadcastEnabled = false;
|
|
_config.Current.BroadcastTtl = DateTime.MinValue;
|
|
_config.Save();
|
|
|
|
_mediator.Publish(new BroadcastStatusChangedMessage(false, null));
|
|
}
|
|
}
|
|
|
|
private void OnEnableBroadcast(EnableBroadcastMessage msg)
|
|
{
|
|
_ = RequireConnectionAsync(nameof(OnEnableBroadcast), async () =>
|
|
{
|
|
try
|
|
{
|
|
GroupBroadcastRequestDto? groupDto = null;
|
|
if (_config.Current.SyncshellFinderEnabled && _config.Current.SelectedFinderSyncshell != null)
|
|
{
|
|
groupDto = new GroupBroadcastRequestDto
|
|
{
|
|
HashedCID = msg.HashedCid,
|
|
GID = _config.Current.SelectedFinderSyncshell,
|
|
Enabled = msg.Enabled,
|
|
};
|
|
}
|
|
|
|
await _apiController.SetBroadcastStatus(msg.HashedCid, msg.Enabled, groupDto).ConfigureAwait(false);
|
|
|
|
_logger.LogDebug("Broadcast {Status} for {Cid}", msg.Enabled ? "enabled" : "disabled", msg.HashedCid);
|
|
|
|
if (!msg.Enabled)
|
|
{
|
|
_config.Current.BroadcastEnabled = false;
|
|
_config.Current.BroadcastTtl = DateTime.MinValue;
|
|
_config.Save();
|
|
|
|
_mediator.Publish(new BroadcastStatusChangedMessage(false, null));
|
|
Mediator.Publish(new EventMessage(new Services.Events.Event(nameof(BroadcastService), Services.Events.EventSeverity.Informational, $"Disabled Lightfinder for Player: {msg.HashedCid}")));
|
|
return;
|
|
}
|
|
|
|
_waitingForTtlFetch = true;
|
|
|
|
TimeSpan? ttl = await GetBroadcastTtlAsync(msg.HashedCid).ConfigureAwait(false);
|
|
|
|
if (ttl is { } remaining && remaining > TimeSpan.Zero)
|
|
{
|
|
_config.Current.BroadcastTtl = DateTime.UtcNow + remaining;
|
|
_config.Current.BroadcastEnabled = true;
|
|
_config.Save();
|
|
|
|
_logger.LogDebug("Fetched TTL from server: {TTL}", remaining);
|
|
_mediator.Publish(new BroadcastStatusChangedMessage(true, remaining));
|
|
Mediator.Publish(new EventMessage(new Services.Events.Event(nameof(BroadcastService), Services.Events.EventSeverity.Informational, $"Enabled Lightfinder for Player: {msg.HashedCid}")));
|
|
}
|
|
else
|
|
{
|
|
_logger.LogWarning("No valid TTL returned after enabling broadcast. Disabling.");
|
|
_config.Current.BroadcastEnabled = false;
|
|
_config.Current.BroadcastTtl = DateTime.MinValue;
|
|
_config.Save();
|
|
|
|
_mediator.Publish(new BroadcastStatusChangedMessage(false, null));
|
|
}
|
|
|
|
_waitingForTtlFetch = false;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Failed to toggle broadcast for {Cid}", msg.HashedCid);
|
|
_waitingForTtlFetch = false;
|
|
}
|
|
});
|
|
}
|
|
|
|
private void OnBroadcastStatusChanged(BroadcastStatusChangedMessage msg)
|
|
{
|
|
_config.Current.BroadcastEnabled = msg.Enabled;
|
|
_config.Save();
|
|
}
|
|
|
|
public async Task<bool> CheckIfBroadcastingAsync(string targetCid)
|
|
{
|
|
bool result = false;
|
|
await RequireConnectionAsync(nameof(CheckIfBroadcastingAsync), async () =>
|
|
{
|
|
try
|
|
{
|
|
_logger.LogDebug("[BroadcastCheck] Checking CID: {cid}", targetCid);
|
|
|
|
var info = await _apiController.IsUserBroadcasting(targetCid).ConfigureAwait(false);
|
|
result = info?.TTL > TimeSpan.Zero;
|
|
|
|
|
|
_logger.LogDebug("[BroadcastCheck] Result for {cid}: {result} (TTL: {ttl}, GID: {gid})", targetCid, result, info?.TTL, info?.GID);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Failed to check broadcast status for {cid}", targetCid);
|
|
}
|
|
}).ConfigureAwait(false);
|
|
|
|
|
|
return result;
|
|
}
|
|
|
|
public async Task<TimeSpan?> GetBroadcastTtlAsync(string cid)
|
|
{
|
|
TimeSpan? ttl = null;
|
|
await RequireConnectionAsync(nameof(GetBroadcastTtlAsync), async () => {
|
|
try
|
|
{
|
|
ttl = await _apiController.GetBroadcastTtl(cid).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Failed to fetch broadcast TTL for {cid}", cid);
|
|
}
|
|
}).ConfigureAwait(false);
|
|
return ttl;
|
|
}
|
|
|
|
public async Task<Dictionary<string, BroadcastStatusInfoDto?>> AreUsersBroadcastingAsync(List<string> hashedCids)
|
|
{
|
|
Dictionary<string, BroadcastStatusInfoDto?> result = new();
|
|
|
|
await RequireConnectionAsync(nameof(AreUsersBroadcastingAsync), async () =>
|
|
{
|
|
try
|
|
{
|
|
var batch = await _apiController.AreUsersBroadcasting(hashedCids).ConfigureAwait(false);
|
|
|
|
if (batch?.Results != null)
|
|
{
|
|
foreach (var kv in batch.Results)
|
|
result[kv.Key] = kv.Value;
|
|
}
|
|
|
|
_logger.LogTrace("Batch broadcast status check complete for {Count} CIDs", hashedCids.Count);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Failed to batch check broadcast status");
|
|
}
|
|
}).ConfigureAwait(false);
|
|
|
|
return result;
|
|
}
|
|
|
|
|
|
|
|
public async void ToggleBroadcast()
|
|
{
|
|
if (!IsLightFinderAvailable)
|
|
{
|
|
_logger.LogWarning("ToggleBroadcast - Lightfinder is not available.");
|
|
return;
|
|
}
|
|
|
|
await RequireConnectionAsync(nameof(ToggleBroadcast), async () =>
|
|
{
|
|
var cooldown = RemainingCooldown;
|
|
if (!_config.Current.BroadcastEnabled && cooldown is { } cd && cd > TimeSpan.Zero)
|
|
{
|
|
_logger.LogWarning("Cooldown active. Must wait {Remaining}s before re-enabling.", cd.TotalSeconds);
|
|
return;
|
|
}
|
|
|
|
var hashedCid = (await _dalamudUtil.GetCIDAsync().ConfigureAwait(false)).ToString().GetHash256();
|
|
|
|
try
|
|
{
|
|
var isCurrentlyBroadcasting = await CheckIfBroadcastingAsync(hashedCid).ConfigureAwait(false);
|
|
var newStatus = !isCurrentlyBroadcasting;
|
|
|
|
if (!newStatus)
|
|
{
|
|
_lastForcedDisableTime = DateTime.UtcNow;
|
|
_logger.LogDebug("Manual disable: cooldown timer started.");
|
|
}
|
|
|
|
_logger.LogDebug("Toggling broadcast. Server currently broadcasting: {ServerStatus}, setting to: {NewStatus}", isCurrentlyBroadcasting, newStatus);
|
|
|
|
_mediator.Publish(new EnableBroadcastMessage(hashedCid, newStatus));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Failed to determine current broadcast status for toggle");
|
|
}
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async void OnTick(PriorityFrameworkUpdateMessage _)
|
|
{
|
|
if (!IsLightFinderAvailable)
|
|
return;
|
|
|
|
if (_config?.Current == null)
|
|
return;
|
|
|
|
if ((DateTime.UtcNow - _lastTtlCheck).TotalSeconds < 1)
|
|
return;
|
|
|
|
_lastTtlCheck = DateTime.UtcNow;
|
|
|
|
await RequireConnectionAsync(nameof(OnTick), async () => {
|
|
if (!_syncedOnStartup && _config.Current.BroadcastEnabled)
|
|
{
|
|
_syncedOnStartup = true;
|
|
try
|
|
{
|
|
string hashedCid = (await _dalamudUtil.GetCIDAsync().ConfigureAwait(false)).ToString().GetHash256();
|
|
TimeSpan? ttl = await GetBroadcastTtlAsync(hashedCid).ConfigureAwait(false);
|
|
if (ttl is { }
|
|
remaining && remaining > TimeSpan.Zero)
|
|
{
|
|
_config.Current.BroadcastTtl = DateTime.UtcNow + remaining;
|
|
_config.Current.BroadcastEnabled = true;
|
|
_config.Save();
|
|
_logger.LogDebug("Refreshed broadcast TTL from server on first OnTick: {TTL}", remaining);
|
|
}
|
|
else
|
|
{
|
|
_logger.LogWarning("No valid TTL found on OnTick. Disabling broadcast state.");
|
|
_config.Current.BroadcastEnabled = false;
|
|
_config.Current.BroadcastTtl = DateTime.MinValue;
|
|
_config.Save();
|
|
_mediator.Publish(new BroadcastStatusChangedMessage(false, null));
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Failed to refresh TTL in OnTick");
|
|
}
|
|
}
|
|
if (_config.Current.BroadcastEnabled)
|
|
{
|
|
if (_waitingForTtlFetch)
|
|
{
|
|
_logger.LogDebug("OnTick skipped: waiting for TTL fetch");
|
|
return;
|
|
}
|
|
|
|
DateTime expiry = _config.Current.BroadcastTtl;
|
|
TimeSpan remaining = expiry - DateTime.UtcNow;
|
|
_remainingTtl = remaining > TimeSpan.Zero ? remaining : null;
|
|
if (_remainingTtl == null)
|
|
{
|
|
_logger.LogDebug("Broadcast TTL expired. Disabling broadcast locally.");
|
|
_config.Current.BroadcastEnabled = false;
|
|
_config.Current.BroadcastTtl = DateTime.MinValue;
|
|
_config.Save();
|
|
_mediator.Publish(new BroadcastStatusChangedMessage(false, null));
|
|
}
|
|
}
|
|
else
|
|
{
|
|
_remainingTtl = null;
|
|
}
|
|
}).ConfigureAwait(false);
|
|
}
|
|
} |