add analyzers and api

This commit is contained in:
Stanley Dimant
2022-10-03 15:58:51 +02:00
parent 3b9b260ab3
commit 260c4a48ee
34 changed files with 435 additions and 265 deletions

View File

@@ -33,7 +33,7 @@ public partial class ApiController
public async Task DeleteAllMyFiles()
{
await _mareHub!.SendAsync(Api.SendFileDeleteAllFiles);
await _mareHub!.SendAsync(Api.SendFileDeleteAllFiles).ConfigureAwait(false);
}
private async Task<string> DownloadFile(int downloadId, string hash, Uri downloadUri, CancellationToken ct)
@@ -44,7 +44,7 @@ public partial class ApiController
{
try
{
CurrentDownloads[downloadId].Single(f => f.Hash == hash).Transferred = e.BytesReceived;
CurrentDownloads[downloadId].Single(f => string.Equals(f.Hash, hash, StringComparison.Ordinal)).Transferred = e.BytesReceived;
}
catch (Exception ex)
{
@@ -61,11 +61,11 @@ public partial class ApiController
try
{
await wc.DownloadFileTaskAsync(downloadUri, fileName);
await wc.DownloadFileTaskAsync(downloadUri, fileName).ConfigureAwait(false);
}
catch { }
CurrentDownloads[downloadId].Single(f => f.Hash == hash).Transferred = CurrentDownloads[downloadId].Single(f => f.Hash == hash).Total;
CurrentDownloads[downloadId].Single(f => string.Equals(f.Hash, hash, StringComparison.Ordinal)).Transferred = CurrentDownloads[downloadId].Single(f => string.Equals(f.Hash, hash, StringComparison.Ordinal)).Total;
wc.DownloadProgressChanged -= progChanged;
return fileName;
@@ -78,7 +78,7 @@ public partial class ApiController
DownloadStarted?.Invoke();
try
{
await DownloadFilesInternal(currentDownloadId, fileReplacementDto, ct);
await DownloadFilesInternal(currentDownloadId, fileReplacementDto, ct).ConfigureAwait(false);
}
catch
{
@@ -94,8 +94,8 @@ public partial class ApiController
{
Logger.Debug("Downloading files (Download ID " + currentDownloadId + ")");
List<DownloadFileDto> downloadFileInfoFromService = new List<DownloadFileDto>();
downloadFileInfoFromService.AddRange(await _mareHub!.InvokeAsync<List<DownloadFileDto>>(Api.InvokeGetFilesSizes, fileReplacementDto.Select(f => f.Hash).ToList(), ct));
List<DownloadFileDto> downloadFileInfoFromService = new();
downloadFileInfoFromService.AddRange(await _mareHub!.InvokeAsync<List<DownloadFileDto>>(Api.InvokeGetFilesSizes, fileReplacementDto.Select(f => f.Hash).ToList(), ct).ConfigureAwait(false));
Logger.Debug("Files with size 0 or less: " + string.Join(", ", downloadFileInfoFromService.Where(f => f.Size <= 0).Select(f => f.Hash)));
@@ -104,7 +104,7 @@ public partial class ApiController
foreach (var dto in downloadFileInfoFromService.Where(c => c.IsForbidden))
{
if (ForbiddenTransfers.All(f => f.Hash != dto.Hash))
if (ForbiddenTransfers.All(f => !string.Equals(f.Hash, dto.Hash, StringComparison.Ordinal)))
{
ForbiddenTransfers.Add(new DownloadFileTransfer(dto));
}
@@ -118,7 +118,7 @@ public partial class ApiController
async (file, token) =>
{
var hash = file.Hash;
var tempFile = await DownloadFile(currentDownloadId, file.Hash, file.DownloadUri, token);
var tempFile = await DownloadFile(currentDownloadId, file.Hash, file.DownloadUri, token).ConfigureAwait(false);
if (token.IsCancellationRequested)
{
File.Delete(tempFile);
@@ -128,16 +128,16 @@ public partial class ApiController
return;
}
var tempFileData = await File.ReadAllBytesAsync(tempFile, token);
var tempFileData = await File.ReadAllBytesAsync(tempFile, token).ConfigureAwait(false);
var extractedFile = LZ4Codec.Unwrap(tempFileData);
File.Delete(tempFile);
var filePath = Path.Combine(_pluginConfiguration.CacheFolder, file.Hash);
await File.WriteAllBytesAsync(filePath, extractedFile, token);
await File.WriteAllBytesAsync(filePath, extractedFile, token).ConfigureAwait(false);
var fi = new FileInfo(filePath);
Func<DateTime> RandomDayFunc()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
DateTime start = new(1995, 1, 1);
Random gen = new();
int range = (DateTime.Today - start).Days;
return () => start.AddDays(gen.Next(range));
}
@@ -155,7 +155,7 @@ public partial class ApiController
Logger.Warn(ex.Message);
Logger.Warn(ex.StackTrace);
}
});
}).ConfigureAwait(false);
Logger.Debug("Download complete, removing " + currentDownloadId);
CancelDownload(currentDownloadId);
@@ -163,7 +163,7 @@ public partial class ApiController
public async Task PushCharacterData(CharacterCacheDto character, List<string> visibleCharacterIds)
{
if (!IsConnected || SecretKey == "-") return;
if (!IsConnected || string.Equals(SecretKey, "-", StringComparison.Ordinal)) return;
Logger.Debug("Sending Character data to service " + ApiUri);
CancelUpload();
@@ -172,7 +172,7 @@ public partial class ApiController
Logger.Verbose("New Token Created");
List<string> unverifiedUploadHashes = new();
foreach (var item in character.FileReplacements.SelectMany(c => c.Value.Where(f => string.IsNullOrEmpty(f.FileSwapPath)).Select(v => v.Hash).Distinct()).Distinct().ToList())
foreach (var item in character.FileReplacements.SelectMany(c => c.Value.Where(f => string.IsNullOrEmpty(f.FileSwapPath)).Select(v => v.Hash).Distinct(StringComparer.Ordinal)).Distinct(StringComparer.Ordinal).ToList())
{
if (!_verifiedUploadedHashes.Contains(item))
{
@@ -183,7 +183,7 @@ public partial class ApiController
if (unverifiedUploadHashes.Any())
{
Logger.Debug("Verifying " + unverifiedUploadHashes.Count + " files");
var filesToUpload = await _mareHub!.InvokeAsync<List<UploadFileDto>>(Api.InvokeFileSendFiles, unverifiedUploadHashes, uploadToken);
var filesToUpload = await _mareHub!.InvokeAsync<List<UploadFileDto>>(Api.InvokeFileSendFiles, unverifiedUploadHashes, uploadToken).ConfigureAwait(false);
foreach (var file in filesToUpload.Where(f => !f.IsForbidden))
{
@@ -203,7 +203,7 @@ public partial class ApiController
foreach (var file in filesToUpload.Where(c => c.IsForbidden))
{
if (ForbiddenTransfers.All(f => f.Hash != file.Hash))
if (ForbiddenTransfers.All(f => !string.Equals(f.Hash, file.Hash, StringComparison.Ordinal)))
{
ForbiddenTransfers.Add(new UploadFileTransfer(file)
{
@@ -217,9 +217,9 @@ public partial class ApiController
foreach (var file in CurrentUploads.Where(f => f.CanBeTransferred && !f.IsTransferred).ToList())
{
Logger.Debug("Compressing and uploading " + file);
var data = await GetCompressedFileData(file.Hash, uploadToken);
CurrentUploads.Single(e => e.Hash == data.Item1).Total = data.Item2.Length;
await UploadFile(data.Item2, file.Hash, uploadToken);
var data = await GetCompressedFileData(file.Hash, uploadToken).ConfigureAwait(false);
CurrentUploads.Single(e => string.Equals(e.Hash, data.Item1, StringComparison.Ordinal)).Total = data.Item2.Length;
await UploadFile(data.Item2, file.Hash, uploadToken).ConfigureAwait(false);
if (!uploadToken.IsCancellationRequested) continue;
Logger.Warn("Cancel in filesToUpload loop detected");
CurrentUploads.Clear();
@@ -233,12 +233,12 @@ public partial class ApiController
}
Logger.Debug("Upload tasks complete, waiting for server to confirm");
var anyUploadsOpen = await _mareHub!.InvokeAsync<bool>(Api.InvokeFileIsUploadFinished, uploadToken);
var anyUploadsOpen = await _mareHub!.InvokeAsync<bool>(Api.InvokeFileIsUploadFinished, uploadToken).ConfigureAwait(false);
Logger.Debug("Uploads open: " + anyUploadsOpen);
while (anyUploadsOpen && !uploadToken.IsCancellationRequested)
{
anyUploadsOpen = await _mareHub!.InvokeAsync<bool>(Api.InvokeFileIsUploadFinished, uploadToken);
await Task.Delay(TimeSpan.FromSeconds(0.5), uploadToken);
anyUploadsOpen = await _mareHub!.InvokeAsync<bool>(Api.InvokeFileIsUploadFinished, uploadToken).ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(0.5), uploadToken).ConfigureAwait(false);
Logger.Debug("Waiting for uploads to finish");
}
@@ -257,7 +257,7 @@ public partial class ApiController
if (!uploadToken.IsCancellationRequested)
{
Logger.Info("Pushing character data for " + character.GetHashCode() + " to " + string.Join(", ", visibleCharacterIds));
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
foreach (var item in character.FileReplacements)
{
sb.AppendLine($"FileReplacements for {item.Key}: {item.Value.Count}");
@@ -267,7 +267,7 @@ public partial class ApiController
sb.AppendLine($"GlamourerData for {item.Key}: {!string.IsNullOrEmpty(item.Value)}");
}
Logger.Debug("Chara data contained: " + Environment.NewLine + sb.ToString());
await _mareHub!.InvokeAsync(Api.InvokeUserPushCharacterDataToVisibleClients, character, visibleCharacterIds, uploadToken);
await _mareHub!.InvokeAsync(Api.InvokeUserPushCharacterDataToVisibleClients, character, visibleCharacterIds, uploadToken).ConfigureAwait(false);
}
else
{
@@ -281,7 +281,7 @@ public partial class ApiController
private async Task<(string, byte[])> GetCompressedFileData(string fileHash, CancellationToken uploadToken)
{
var fileCache = _fileDbManager.GetFileCacheByHash(fileHash)!.ResolvedFilepath;
return (fileHash, LZ4Codec.WrapHC(await File.ReadAllBytesAsync(fileCache, uploadToken), 0,
return (fileHash, LZ4Codec.WrapHC(await File.ReadAllBytesAsync(fileCache, uploadToken).ConfigureAwait(false), 0,
(int)new FileInfo(fileCache).Length));
}
@@ -295,15 +295,15 @@ public partial class ApiController
using var ms = new MemoryStream(compressedFile);
var buffer = new byte[chunkSize];
int bytesRead;
while ((bytesRead = await ms.ReadAsync(buffer, 0, chunkSize, token)) > 0 && !token.IsCancellationRequested)
while ((bytesRead = await ms.ReadAsync(buffer, 0, chunkSize, token).ConfigureAwait(false)) > 0 && !token.IsCancellationRequested)
{
CurrentUploads.Single(f => f.Hash == fileHash).Transferred += bytesRead;
CurrentUploads.Single(f => string.Equals(f.Hash, fileHash, StringComparison.Ordinal)).Transferred += bytesRead;
token.ThrowIfCancellationRequested();
yield return bytesRead == chunkSize ? buffer.ToArray() : buffer.Take(bytesRead).ToArray();
}
}
await _mareHub!.SendAsync(Api.SendFileUploadFileStreamAsync, fileHash, AsyncFileData(uploadToken), uploadToken);
await _mareHub!.SendAsync(Api.SendFileUploadFileStreamAsync, fileHash, AsyncFileData(uploadToken), uploadToken).ConfigureAwait(false);
}
public void CancelDownload(int downloadId)

View File

@@ -11,32 +11,32 @@ public partial class ApiController
{
_pluginConfiguration.ClientSecret.Remove(ApiUri);
_pluginConfiguration.Save();
await _mareHub!.SendAsync(Api.SendFileDeleteAllFiles);
await _mareHub!.SendAsync(Api.SendUserDeleteAccount);
await CreateConnections();
await _mareHub!.SendAsync(Api.SendFileDeleteAllFiles).ConfigureAwait(false);
await _mareHub!.SendAsync(Api.SendUserDeleteAccount).ConfigureAwait(false);
await CreateConnections().ConfigureAwait(false);
}
public async Task<List<string>> GetOnlineCharacters()
{
return await _mareHub!.InvokeAsync<List<string>>(Api.InvokeUserGetOnlineCharacters);
return await _mareHub!.InvokeAsync<List<string>>(Api.InvokeUserGetOnlineCharacters).ConfigureAwait(false);
}
public async Task SendPairedClientAddition(string uid)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendUserPairedClientAddition, uid);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendUserPairedClientAddition, uid).ConfigureAwait(false);
}
public async Task SendPairedClientPauseChange(string uid, bool paused)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendUserPairedClientPauseChange, uid, paused);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendUserPairedClientPauseChange, uid, paused).ConfigureAwait(false);
}
public async Task SendPairedClientRemoval(string uid)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendUserPairedClientRemoval, uid);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendUserPairedClientRemoval, uid).ConfigureAwait(false);
}
}

View File

@@ -10,27 +10,27 @@ public partial class ApiController
{
public async Task AddOrUpdateForbiddenFileEntry(ForbiddenFileDto forbiddenFile)
{
await _mareHub!.SendAsync(Api.SendAdminUpdateOrAddForbiddenFile, forbiddenFile);
await _mareHub!.SendAsync(Api.SendAdminUpdateOrAddForbiddenFile, forbiddenFile).ConfigureAwait(false);
}
public async Task DeleteForbiddenFileEntry(ForbiddenFileDto forbiddenFile)
{
await _mareHub!.SendAsync(Api.SendAdminDeleteForbiddenFile, forbiddenFile);
await _mareHub!.SendAsync(Api.SendAdminDeleteForbiddenFile, forbiddenFile).ConfigureAwait(false);
}
public async Task AddOrUpdateBannedUserEntry(BannedUserDto bannedUser)
{
await _mareHub!.SendAsync(Api.SendAdminUpdateOrAddBannedUser, bannedUser);
await _mareHub!.SendAsync(Api.SendAdminUpdateOrAddBannedUser, bannedUser).ConfigureAwait(false);
}
public async Task DeleteBannedUserEntry(BannedUserDto bannedUser)
{
await _mareHub!.SendAsync(Api.SendAdminDeleteBannedUser, bannedUser);
await _mareHub!.SendAsync(Api.SendAdminDeleteBannedUser, bannedUser).ConfigureAwait(false);
}
public async Task RefreshOnlineUsers()
{
AdminOnlineUsers = await _mareHub!.InvokeAsync<List<OnlineUserDto>>(Api.InvokeAdminGetOnlineUsers);
AdminOnlineUsers = await _mareHub!.InvokeAsync<List<OnlineUserDto>>(Api.InvokeAdminGetOnlineUsers).ConfigureAwait(false);
}
public List<OnlineUserDto> AdminOnlineUsers { get; set; } = new List<OnlineUserDto>();

View File

@@ -17,10 +17,10 @@ public partial class ApiController
private void UpdateLocalClientPairsCallback(ClientPairDto dto)
{
var entry = PairedClients.SingleOrDefault(e => e.OtherUID == dto.OtherUID);
var entry = PairedClients.SingleOrDefault(e => string.Equals(e.OtherUID, dto.OtherUID, System.StringComparison.Ordinal));
if (dto.IsRemoved)
{
PairedClients.RemoveAll(p => p.OtherUID == dto.OtherUID);
PairedClients.RemoveAll(p => string.Equals(p.OtherUID, dto.OtherUID, System.StringComparison.Ordinal));
return;
}
if (entry == null)
@@ -43,7 +43,7 @@ public partial class ApiController
private void UpdateOrAddBannedUserCallback(BannedUserDto obj)
{
var user = AdminBannedUsers.SingleOrDefault(b => b.CharacterHash == obj.CharacterHash);
var user = AdminBannedUsers.SingleOrDefault(b => string.Equals(b.CharacterHash, obj.CharacterHash, System.StringComparison.Ordinal));
if (user == null)
{
AdminBannedUsers.Add(obj);
@@ -56,12 +56,12 @@ public partial class ApiController
private void DeleteBannedUserCallback(BannedUserDto obj)
{
AdminBannedUsers.RemoveAll(a => a.CharacterHash == obj.CharacterHash);
AdminBannedUsers.RemoveAll(a => string.Equals(a.CharacterHash, obj.CharacterHash, System.StringComparison.Ordinal));
}
private void UpdateOrAddForbiddenFileCallback(ForbiddenFileDto obj)
{
var user = AdminForbiddenFiles.SingleOrDefault(b => b.Hash == obj.Hash);
var user = AdminForbiddenFiles.SingleOrDefault(b => string.Equals(b.Hash, obj.Hash, System.StringComparison.Ordinal));
if (user == null)
{
AdminForbiddenFiles.Add(obj);
@@ -74,18 +74,18 @@ public partial class ApiController
private void DeleteForbiddenFileCallback(ForbiddenFileDto obj)
{
AdminForbiddenFiles.RemoveAll(f => f.Hash == obj.Hash);
AdminForbiddenFiles.RemoveAll(f => string.Equals(f.Hash, obj.Hash, System.StringComparison.Ordinal));
}
private void GroupPairChangedCallback(GroupPairDto dto)
{
if (dto.IsRemoved.GetValueOrDefault(false))
{
GroupPairedClients.RemoveAll(g => g.GroupGID == dto.GroupGID && g.UserUID == dto.UserUID);
GroupPairedClients.RemoveAll(g => string.Equals(g.GroupGID, dto.GroupGID, System.StringComparison.Ordinal) && string.Equals(g.UserUID, dto.UserUID, System.StringComparison.Ordinal));
return;
}
var existingUser = GroupPairedClients.FirstOrDefault(f => f.GroupGID == dto.GroupGID && f.UserUID == dto.UserUID);
var existingUser = GroupPairedClients.FirstOrDefault(f => string.Equals(f.GroupGID, dto.GroupGID, System.StringComparison.Ordinal) && string.Equals(f.UserUID, dto.UserUID, System.StringComparison.Ordinal));
if (existingUser == null)
{
GroupPairedClients.Add(dto);
@@ -101,16 +101,16 @@ public partial class ApiController
{
if (dto.IsDeleted.GetValueOrDefault(false))
{
Groups.RemoveAll(g => g.GID == dto.GID);
GroupPairedClients.RemoveAll(g => g.GroupGID == dto.GID);
Groups.RemoveAll(g => string.Equals(g.GID, dto.GID, System.StringComparison.Ordinal));
GroupPairedClients.RemoveAll(g => string.Equals(g.GroupGID, dto.GID, System.StringComparison.Ordinal));
return;
}
var existingGroup = Groups.FirstOrDefault(g => g.GID == dto.GID);
var existingGroup = Groups.FirstOrDefault(g => string.Equals(g.GID, dto.GID, System.StringComparison.Ordinal));
if (existingGroup == null)
{
Groups.Add(dto);
GroupPairedClients.AddRange(await _mareHub!.InvokeAsync<List<GroupPairDto>>(Api.InvokeGroupGetUsersInGroup, dto.GID));
GroupPairedClients.AddRange(await _mareHub!.InvokeAsync<List<GroupPairDto>>(Api.InvokeGroupGetUsersInGroup, dto.GID).ConfigureAwait(false));
return;
}

View File

@@ -9,79 +9,79 @@ public partial class ApiController
{
public async Task<GroupCreatedDto> CreateGroup()
{
if (!IsConnected || SecretKey == "-") return new GroupCreatedDto();
return await _mareHub!.InvokeAsync<GroupCreatedDto>(Api.InvokeGroupCreate);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return new GroupCreatedDto();
return await _mareHub!.InvokeAsync<GroupCreatedDto>(Api.InvokeGroupCreate).ConfigureAwait(false);
}
public async Task<bool> ChangeGroupPassword(string gid, string newpassword)
{
if (!IsConnected || SecretKey == "-") return false;
return await _mareHub!.InvokeAsync<bool>(Api.InvokeGroupChangePassword, gid, newpassword);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return false;
return await _mareHub!.InvokeAsync<bool>(Api.InvokeGroupChangePassword, gid, newpassword).ConfigureAwait(false);
}
public async Task<List<GroupDto>> GetGroups()
{
if (!IsConnected || SecretKey == "-") return new List<GroupDto>();
return await _mareHub!.InvokeAsync<List<GroupDto>>(Api.InvokeGroupGetGroups);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return new List<GroupDto>();
return await _mareHub!.InvokeAsync<List<GroupDto>>(Api.InvokeGroupGetGroups).ConfigureAwait(false);
}
public async Task<List<GroupPairDto>> GetUsersInGroup(string gid)
{
if (!IsConnected || SecretKey == "-") return new List<GroupPairDto>();
return await _mareHub!.InvokeAsync<List<GroupPairDto>>(Api.InvokeGroupGetUsersInGroup, gid);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return new List<GroupPairDto>();
return await _mareHub!.InvokeAsync<List<GroupPairDto>>(Api.InvokeGroupGetUsersInGroup, gid).ConfigureAwait(false);
}
public async Task<bool> SendGroupJoin(string gid, string password)
{
if (!IsConnected || SecretKey == "-") return false;
return await _mareHub!.InvokeAsync<bool>(Api.InvokeGroupJoin, gid, password);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return false;
return await _mareHub!.InvokeAsync<bool>(Api.InvokeGroupJoin, gid, password).ConfigureAwait(false);
}
public async Task SendGroupChangeInviteState(string gid, bool opened)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendGroupChangeInviteState, gid, opened);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendGroupChangeInviteState, gid, opened).ConfigureAwait(false);
}
public async Task SendDeleteGroup(string gid)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendGroupDelete, gid);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendGroupDelete, gid).ConfigureAwait(false);
}
public async Task SendChangeUserPinned(string gid, string uid, bool isPinned)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendGroupChangePinned, gid, uid, isPinned);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendGroupChangePinned, gid, uid, isPinned).ConfigureAwait(false);
}
public async Task SendClearGroup(string gid)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendGroupClear, gid);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendGroupClear, gid).ConfigureAwait(false);
}
public async Task SendLeaveGroup(string gid)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendGroupLeave, gid);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendGroupLeave, gid).ConfigureAwait(false);
}
public async Task SendPauseGroup(string gid, bool isPaused)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendGroupPause, gid, isPaused);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendGroupPause, gid, isPaused).ConfigureAwait(false);
}
public async Task SendRemoveUserFromGroup(string gid, string uid)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendGroupRemoveUser, gid, uid);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendGroupRemoveUser, gid, uid).ConfigureAwait(false);
}
public async Task ChangeOwnerOfGroup(string gid, string uid)
{
if (!IsConnected || SecretKey == "-") return;
await _mareHub!.SendAsync(Api.SendGroupChangeOwner, gid, uid);
if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return;
await _mareHub!.SendAsync(Api.SendGroupChangeOwner, gid, uid).ConfigureAwait(false);
}
}

View File

@@ -33,8 +33,11 @@ public partial class ApiController : IDisposable
private HubConnection? _mareHub;
private CancellationTokenSource? _uploadCancellationTokenSource = new();
private CancellationTokenSource? _healthCheckTokenSource = new();
private ConnectionDto? _connectionDto;
public ServerInfoDto ServerInfo => _connectionDto?.ServerInfo ?? new ServerInfoDto();
public SystemInfoDto SystemInfoDto { get; private set; } = new();
public bool IsModerator => (_connectionDto?.IsAdmin ?? false) || (_connectionDto?.IsModerator ?? false);
@@ -51,7 +54,7 @@ public partial class ApiController : IDisposable
_dalamudUtil.LogIn += DalamudUtilOnLogIn;
_dalamudUtil.LogOut += DalamudUtilOnLogOut;
ServerState = ServerState.Offline;
_verifiedUploadedHashes = new();
_verifiedUploadedHashes = new(StringComparer.Ordinal);
if (_dalamudUtil.IsLoggedIn)
{
@@ -61,7 +64,7 @@ public partial class ApiController : IDisposable
private void DalamudUtilOnLogOut()
{
Task.Run(async () => await StopConnection(_connectionCancellationTokenSource.Token));
Task.Run(async () => await StopConnection(_connectionCancellationTokenSource.Token).ConfigureAwait(false));
ServerState = ServerState.Offline;
}
@@ -108,10 +111,10 @@ public partial class ApiController : IDisposable
public bool ServerAlive => ServerState is ServerState.Connected or ServerState.RateLimited or ServerState.Unauthorized or ServerState.Disconnected;
public Dictionary<string, string> ServerDictionary => new Dictionary<string, string>()
public Dictionary<string, string> ServerDictionary => new Dictionary<string, string>(StringComparer.Ordinal)
{ { MainServiceUri, MainServer } }
.Concat(_pluginConfiguration.CustomServerList)
.ToDictionary(k => k.Key, k => k.Value);
.ToDictionary(k => k.Key, k => k.Value, StringComparer.Ordinal);
public string UID => _connectionDto?.UID ?? string.Empty;
public string DisplayName => _connectionDto?.UID ?? string.Empty;
@@ -138,11 +141,11 @@ public partial class ApiController : IDisposable
Logger.Info("Not recreating Connection, paused");
ServerState = ServerState.Disconnected;
_connectionDto = null;
await StopConnection(_connectionCancellationTokenSource.Token);
await StopConnection(_connectionCancellationTokenSource.Token).ConfigureAwait(false);
return;
}
await StopConnection(_connectionCancellationTokenSource.Token);
await StopConnection(_connectionCancellationTokenSource.Token).ConfigureAwait(false);
Logger.Info("Recreating Connection");
@@ -154,11 +157,11 @@ public partial class ApiController : IDisposable
{
if (string.IsNullOrEmpty(SecretKey))
{
await Task.Delay(TimeSpan.FromSeconds(2));
await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
continue;
}
await StopConnection(token);
await StopConnection(token).ConfigureAwait(false);
try
{
@@ -167,32 +170,32 @@ public partial class ApiController : IDisposable
while (!_dalamudUtil.IsPlayerPresent && !token.IsCancellationRequested)
{
Logger.Debug("Player not loaded in yet, waiting");
await Task.Delay(TimeSpan.FromSeconds(1), token);
await Task.Delay(TimeSpan.FromSeconds(1), token).ConfigureAwait(false);
}
if (token.IsCancellationRequested) break;
_mareHub = BuildHubConnection(Api.Path);
await _mareHub.StartAsync(token);
await _mareHub.StartAsync(token).ConfigureAwait(false);
_mareHub.On<SystemInfoDto>(Api.OnUpdateSystemInfo, (dto) => SystemInfoDto = dto);
_connectionDto =
await _mareHub.InvokeAsync<ConnectionDto>(Api.InvokeHeartbeat, _dalamudUtil.PlayerNameHashed, token);
await _mareHub.InvokeAsync<ConnectionDto>(Api.InvokeHeartbeat, _dalamudUtil.PlayerNameHashed, token).ConfigureAwait(false);
ServerState = ServerState.Connected;
if (_connectionDto.ServerVersion != Api.Version)
{
ServerState = ServerState.VersionMisMatch;
await StopConnection(token);
await StopConnection(token).ConfigureAwait(false);
return;
}
if (ServerState is ServerState.Connected) // user is authorized && server is legit
{
await InitializeData(token);
await InitializeData(token).ConfigureAwait(false);
_mareHub.Closed += MareHubOnClosed;
_mareHub.Reconnecting += MareHubOnReconnecting;
@@ -206,7 +209,7 @@ public partial class ApiController : IDisposable
Logger.Warn(ex.StackTrace ?? string.Empty);
ServerState = ServerState.RateLimited;
await StopConnection(token);
await StopConnection(token).ConfigureAwait(false);
return;
}
catch (HttpRequestException ex)
@@ -218,14 +221,14 @@ public partial class ApiController : IDisposable
if (ex.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
ServerState = ServerState.Unauthorized;
await StopConnection(token);
await StopConnection(token).ConfigureAwait(false);
return;
}
else
{
ServerState = ServerState.Offline;
Logger.Info("Failed to establish connection, retrying");
await Task.Delay(TimeSpan.FromSeconds(new Random().Next(5, 20)), token);
await Task.Delay(TimeSpan.FromSeconds(new Random().Next(5, 20)), token).ConfigureAwait(false);
}
}
catch (Exception ex)
@@ -234,7 +237,7 @@ public partial class ApiController : IDisposable
Logger.Warn(ex.Message);
Logger.Warn(ex.StackTrace ?? string.Empty);
Logger.Info("Failed to establish connection, retrying");
await Task.Delay(TimeSpan.FromSeconds(new Random().Next(5, 20)), token);
await Task.Delay(TimeSpan.FromSeconds(new Random().Next(5, 20)), token).ConfigureAwait(false);
}
}
}
@@ -245,6 +248,21 @@ public partial class ApiController : IDisposable
return Task.CompletedTask;
}
private async Task ClientHealthCheck(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
if (ct.IsCancellationRequested) break;
var needsRestart = await _mareHub!.InvokeAsync<bool>(Api.InvokeCheckClientHealth, ct).ConfigureAwait(false);
Logger.Debug("Checked Client Health State, healthy: " + !needsRestart);
if (needsRestart)
{
_ = CreateConnections();
}
}
}
private async Task InitializeData(CancellationToken token)
{
if (_mareHub == null) return;
@@ -263,22 +281,22 @@ public partial class ApiController : IDisposable
_mareHub.On<GroupPairDto>(Api.OnGroupUserChange, GroupPairChangedCallback);
PairedClients =
await _mareHub!.InvokeAsync<List<ClientPairDto>>(Api.InvokeUserGetPairedClients, token);
Groups = await GetGroups();
await _mareHub!.InvokeAsync<List<ClientPairDto>>(Api.InvokeUserGetPairedClients, token).ConfigureAwait(false);
Groups = await GetGroups().ConfigureAwait(false);
GroupPairedClients.Clear();
foreach (var group in Groups)
{
GroupPairedClients.AddRange(await GetUsersInGroup(group.GID));
GroupPairedClients.AddRange(await GetUsersInGroup(group.GID).ConfigureAwait(false));
}
if (IsModerator)
{
AdminForbiddenFiles =
await _mareHub.InvokeAsync<List<ForbiddenFileDto>>(Api.InvokeAdminGetForbiddenFiles,
token);
token).ConfigureAwait(false);
AdminBannedUsers =
await _mareHub.InvokeAsync<List<BannedUserDto>>(Api.InvokeAdminGetBannedUsers,
token);
token).ConfigureAwait(false);
_mareHub.On<BannedUserDto>(Api.OnAdminUpdateOrAddBannedUser,
UpdateOrAddBannedUserCallback);
_mareHub.On<BannedUserDto>(Api.OnAdminDeleteBannedUser, DeleteBannedUserCallback);
@@ -288,6 +306,11 @@ public partial class ApiController : IDisposable
DeleteForbiddenFileCallback);
}
_healthCheckTokenSource?.Cancel();
_healthCheckTokenSource?.Dispose();
_healthCheckTokenSource = new CancellationTokenSource();
_ = ClientHealthCheck(_healthCheckTokenSource.Token);
Connected?.Invoke();
}
@@ -298,7 +321,7 @@ public partial class ApiController : IDisposable
_dalamudUtil.LogIn -= DalamudUtilOnLogIn;
_dalamudUtil.LogOut -= DalamudUtilOnLogOut;
Task.Run(async () => await StopConnection(_connectionCancellationTokenSource.Token));
Task.Run(async () => await StopConnection(_connectionCancellationTokenSource.Token).ConfigureAwait(false));
_connectionCancellationTokenSource?.Cancel();
}
@@ -332,6 +355,7 @@ public partial class ApiController : IDisposable
private Task MareHubOnReconnecting(Exception? arg)
{
_healthCheckTokenSource?.Cancel();
ServerState = ServerState.Disconnected;
Logger.Warn("Connection closed... Reconnecting");
Logger.Warn(arg?.Message ?? string.Empty);
@@ -350,8 +374,8 @@ public partial class ApiController : IDisposable
_mareHub.Closed -= MareHubOnClosed;
_mareHub.Reconnecting -= MareHubOnReconnecting;
_mareHub.Reconnected -= MareHubOnReconnected;
await _mareHub.StopAsync(token);
await _mareHub.DisposeAsync();
await _mareHub.StopAsync(token).ConfigureAwait(false);
await _mareHub.DisposeAsync().ConfigureAwait(false);
CurrentUploads.Clear();
CurrentDownloads.Clear();
_uploadCancellationTokenSource?.Cancel();
@@ -363,7 +387,7 @@ public partial class ApiController : IDisposable
{
while (ServerState != ServerState.Offline)
{
await Task.Delay(16);
await Task.Delay(16).ConfigureAwait(false);
}
}
}