Compare commits
2 Commits
6d955f245a
...
fd0bca5c7c
| Author | SHA1 | Date | |
|---|---|---|---|
| fd0bca5c7c | |||
| 3e717522c2 |
@@ -18,7 +18,7 @@ namespace HermesSocketServer.Requests
|
||||
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
string groupId = data["group"].ToString()!;
|
||||
Guid groupId = new Guid(data["group"].ToString()!);
|
||||
string path = data["path"].ToString()!;
|
||||
bool? allow = bool.TryParse(data["allow"].ToString()!, out bool a) ? a : null;
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace HermesSocketServer.Requests
|
||||
public class CreateRedeemableAction : IRequest
|
||||
{
|
||||
public string Name => "create_redeemable_action";
|
||||
public string[] RequiredKeys => ["name", "data", "type"];
|
||||
public string[] RequiredKeys => ["name", "has_message", "type", "data"];
|
||||
private ILogger _logger;
|
||||
|
||||
public CreateRedeemableAction(ILogger logger)
|
||||
@@ -19,8 +19,9 @@ namespace HermesSocketServer.Requests
|
||||
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||
{
|
||||
string name = data["name"].ToString()!;
|
||||
string d = data["data"].ToString()!;
|
||||
string type = data["type"].ToString()!;
|
||||
bool hasMessage = data["has_message"].ToString()!.ToLower() == "true";
|
||||
string d = data["data"].ToString()!;
|
||||
IDictionary<string, string> dict = new Dictionary<string, string>();
|
||||
|
||||
try
|
||||
@@ -29,7 +30,7 @@ namespace HermesSocketServer.Requests
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error(ex, $"Failed to parse data on redeemable action while creating action [name: {name}][type: {type}][data: {d}]");
|
||||
_logger.Error(ex, $"Failed to parse data on redeemable action while creating action [name: {name}][type: {type}][has message: {hasMessage}][data: {d}]");
|
||||
return Task.FromResult(RequestResult.Failed("Could not parse the data on this action."));
|
||||
}
|
||||
|
||||
@@ -37,14 +38,15 @@ namespace HermesSocketServer.Requests
|
||||
{
|
||||
UserId = channel.Id,
|
||||
Name = name,
|
||||
Data = dict,
|
||||
Type = type,
|
||||
HasMessage = hasMessage,
|
||||
Data = dict,
|
||||
};
|
||||
|
||||
bool result = channel.Actions.Set(name, action);
|
||||
if (result)
|
||||
{
|
||||
_logger.Information($"Added redeemable action to channel [name: {name}][type: {type}][channel: {channel.Id}]");
|
||||
_logger.Information($"Added redeemable action to channel [name: {name}][type: {type}][has message: {hasMessage}][channel: {channel.Id}]");
|
||||
return Task.FromResult(RequestResult.Successful(action));
|
||||
}
|
||||
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using HermesSocketLibrary.db;
|
||||
using HermesSocketServer.Models;
|
||||
using ILogger = Serilog.ILogger;
|
||||
|
||||
@@ -8,28 +7,26 @@ namespace HermesSocketServer.Requests
|
||||
{
|
||||
public string Name => "create_tts_user";
|
||||
public string[] RequiredKeys => ["chatter", "voice"];
|
||||
private Database _database;
|
||||
private readonly ServerConfiguration _configuration;
|
||||
private ILogger _logger;
|
||||
|
||||
public CreateTTSUser(Database database, ServerConfiguration configuration, ILogger logger)
|
||||
public CreateTTSUser(ServerConfiguration configuration, ILogger logger)
|
||||
{
|
||||
_database = database;
|
||||
_configuration = configuration;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||
{
|
||||
if (!long.TryParse(data["chatter"].ToString(), out long chatterId))
|
||||
return RequestResult.Failed("Invalid Twitch user id");
|
||||
return Task.FromResult(RequestResult.Failed("Invalid Twitch user id."));
|
||||
|
||||
data["user"] = channel.Id;
|
||||
data["voice"] = data["voice"].ToString()!;
|
||||
var voiceId = data["voice"].ToString()!;
|
||||
|
||||
var check = await _database.ExecuteScalar("SELECT state FROM \"TtsVoiceState\" WHERE \"userId\" = @user AND \"ttsVoiceId\" = @voice", data) ?? false;
|
||||
if ((check is not bool state || !state) && chatterId != _configuration.Tts.OwnerId)
|
||||
return RequestResult.Failed("Voice is disabled on this channel.");
|
||||
var check = channel.VoiceStates.Get(voiceId)?.Enabled ?? false;
|
||||
if (!check && chatterId != _configuration.Tts.OwnerId)
|
||||
return Task.FromResult(RequestResult.Failed("Voice is disabled on this channel."));
|
||||
|
||||
bool result = channel.Chatters.Set(chatterId.ToString(), new ChatterVoice()
|
||||
{
|
||||
@@ -40,10 +37,10 @@ namespace HermesSocketServer.Requests
|
||||
|
||||
if (result)
|
||||
{
|
||||
_logger.Information($"Selected a tts voice [voice: {data["voice"]}] for user [chatter: {data["chatter"]}] in channel [channel: {data["user"]}]");
|
||||
return RequestResult.Successful(null);
|
||||
_logger.Information($"Selected a tts voice [voice: {voiceId}] for user [chatter: {chatterId}] in channel [channel: {channel.Id}]");
|
||||
return Task.FromResult(RequestResult.Successful(null));
|
||||
}
|
||||
return RequestResult.Failed("Something went wrong when updating the cache.");
|
||||
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ namespace HermesSocketServer.Requests
|
||||
if (result)
|
||||
{
|
||||
var permissions = channel.GroupPermissions.Get().Values
|
||||
.Where(p => p.GroupId == groupId);
|
||||
.Where(p => p.GroupId.ToString() == groupId);
|
||||
|
||||
Task? chattersSave = null;
|
||||
if (channel.Groups.Chatters.TryGetValue(groupId, out var chatters))
|
||||
@@ -32,7 +32,7 @@ namespace HermesSocketServer.Requests
|
||||
{
|
||||
foreach (var chatter in filteredChatters)
|
||||
{
|
||||
var res = chatters.Remove(chatter.ChatterId.ToString());
|
||||
var res = chatters.Remove(chatter.ChatterId.ToString(), fromCascade: true);
|
||||
if (!res)
|
||||
_logger.Warning($"Failed to delete group chatter by id [group chatter id: {chatter.ChatterId}]");
|
||||
}
|
||||
@@ -43,7 +43,7 @@ namespace HermesSocketServer.Requests
|
||||
|
||||
foreach (var permission in permissions)
|
||||
{
|
||||
var res = channel.GroupPermissions.Remove(permission.Id);
|
||||
var res = channel.GroupPermissions.Remove(permission.Id, fromCascade: true);
|
||||
if (!res)
|
||||
_logger.Warning($"Failed to delete group permission by id [group chatter id: {permission.Id}]");
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ namespace HermesSocketServer.Requests
|
||||
public class DeleteGroupChatter : IRequest
|
||||
{
|
||||
public string Name => "delete_group_chatter";
|
||||
public string[] RequiredKeys => ["id", "group"];
|
||||
public string[] RequiredKeys => ["chatter", "group"];
|
||||
private ILogger _logger;
|
||||
|
||||
public DeleteGroupChatter(ILogger logger)
|
||||
@@ -16,7 +16,7 @@ namespace HermesSocketServer.Requests
|
||||
|
||||
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||
{
|
||||
var chatterId = data["id"].ToString()!;
|
||||
var chatterId = data["chatter"].ToString()!;
|
||||
var groupId = data["group"].ToString()!;
|
||||
|
||||
if (!channel.Groups.Chatters.TryGetValue(groupId, out var chatters))
|
||||
|
||||
@@ -30,8 +30,8 @@ namespace HermesSocketServer.Requests
|
||||
|
||||
private class GroupDetails
|
||||
{
|
||||
public required Group Group;
|
||||
public required IEnumerable<GroupChatter> Chatters;
|
||||
public required Group Group { get; set; }
|
||||
public required IEnumerable<GroupChatter> Chatters { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ namespace HermesSocketServer.Requests
|
||||
var id = Guid.NewGuid();
|
||||
string groupId = data["group"].ToString()!;
|
||||
if (!int.TryParse(data["chatter"].ToString()!, out var chatterId))
|
||||
return Task.FromResult(RequestResult.Failed("Priority needs to be an integer."));
|
||||
return Task.FromResult(RequestResult.Failed("Chatter Id needs to be an integer."));
|
||||
string chatterLabel = data["label"].ToString()!;
|
||||
|
||||
var groupChatter = new GroupChatter()
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace HermesSocketServer.Requests
|
||||
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||
{
|
||||
var id = data["id"].ToString()!;
|
||||
string groupId = data["group"].ToString()!;
|
||||
Guid groupId = new Guid(data["group"].ToString()!);
|
||||
string path = data["path"].ToString()!;
|
||||
bool? allow = bool.TryParse(data["allow"].ToString()!, out bool a) ? a : null;
|
||||
|
||||
|
||||
@@ -19,8 +19,9 @@ namespace HermesSocketServer.Requests
|
||||
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||
{
|
||||
string name = data["name"].ToString()!;
|
||||
string d = data["data"].ToString()!;
|
||||
string type = data["type"].ToString()!;
|
||||
bool hasMessage = data["has_message"].ToString()!.ToLower() == "true";
|
||||
string d = data["data"].ToString()!;
|
||||
IDictionary<string, string> dict = new Dictionary<string, string>();
|
||||
|
||||
try
|
||||
@@ -29,7 +30,7 @@ namespace HermesSocketServer.Requests
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error(ex, $"Failed to parse data on redeemable action while updating action [name: {name}][type: {type}][data: {d}]");
|
||||
_logger.Error(ex, $"Failed to parse data on redeemable action while updating action [name: {name}][type: {type}][has message: {hasMessage}][data: {d}]");
|
||||
return Task.FromResult(RequestResult.Failed("Could not parse the data on this action."));
|
||||
}
|
||||
|
||||
@@ -37,14 +38,15 @@ namespace HermesSocketServer.Requests
|
||||
{
|
||||
UserId = channel.Id,
|
||||
Name = name,
|
||||
Data = dict,
|
||||
Type = type,
|
||||
HasMessage = hasMessage,
|
||||
Data = dict,
|
||||
};
|
||||
|
||||
bool result = channel.Actions.Modify(name, action);
|
||||
if (result)
|
||||
{
|
||||
_logger.Information($"Updated redeemable action on channel [name: {name}][type: {type}][channel: {channel.Id}]");
|
||||
_logger.Information($"Updated redeemable action on channel [name: {name}][type: {type}][has message: {hasMessage}][channel: {channel.Id}]");
|
||||
return Task.FromResult(RequestResult.Successful(action));
|
||||
}
|
||||
if (channel.Actions.Get(name) == null)
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using HermesSocketLibrary.db;
|
||||
using HermesSocketServer.Models;
|
||||
using HermesSocketServer.Services;
|
||||
using ILogger = Serilog.ILogger;
|
||||
|
||||
namespace HermesSocketServer.Requests
|
||||
@@ -9,28 +7,27 @@ namespace HermesSocketServer.Requests
|
||||
{
|
||||
public string Name => "update_tts_user";
|
||||
public string[] RequiredKeys => ["chatter", "voice"];
|
||||
private Database _database;
|
||||
private readonly ServerConfiguration _configuration;
|
||||
private ILogger _logger;
|
||||
|
||||
public UpdateTTSUser(Database database, ServerConfiguration configuration, ILogger logger)
|
||||
public UpdateTTSUser(ServerConfiguration configuration, ILogger logger)
|
||||
{
|
||||
_database = database;
|
||||
_configuration = configuration;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
|
||||
public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||
{
|
||||
if (!long.TryParse(data["chatter"].ToString(), out long chatterId))
|
||||
return RequestResult.Failed("Chatter should be an integer, representing the Twitch User Id of the chatter.");
|
||||
return Task.FromResult(RequestResult.Failed("Invalid Twitch user id."));
|
||||
|
||||
data["user"] = channel.Id;
|
||||
var voiceId = data["voice"].ToString()!;
|
||||
|
||||
var check = await _database.ExecuteScalar("SELECT state FROM \"TtsVoiceState\" WHERE \"userId\" = @user AND \"ttsVoiceId\" = @voice", data) ?? false;
|
||||
if ((check is not bool state || !state) && chatterId != _configuration.Tts.OwnerId)
|
||||
return RequestResult.Failed("Voice is either non-existent or disabled on this channel.");
|
||||
var check = channel.VoiceStates.Get(voiceId)?.Enabled ?? false;
|
||||
if (!check && chatterId != _configuration.Tts.OwnerId)
|
||||
return Task.FromResult(RequestResult.Failed("Voice is either non-existent or disabled on this channel."));
|
||||
|
||||
var voice = new ChatterVoice()
|
||||
{
|
||||
@@ -43,9 +40,9 @@ namespace HermesSocketServer.Requests
|
||||
if (result)
|
||||
{
|
||||
_logger.Information($"Updated chatter's selected tts voice on channel [chatter id: {chatterId}][voice id: {voiceId}][channel: {channel.Id}]");
|
||||
return RequestResult.Successful(voice);
|
||||
return Task.FromResult(RequestResult.Successful(voice));
|
||||
}
|
||||
return RequestResult.Failed("Soemthing went wrong when updating the cache.");
|
||||
return Task.FromResult(RequestResult.Failed("Soemthing went wrong when updating the cache."));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,20 +20,20 @@ namespace HermesSocketServer.Requests
|
||||
|
||||
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||
{
|
||||
var id = data["voice"].ToString()!;
|
||||
var state = data["state"].ToString() == "True";
|
||||
var voiceId = data["voice"].ToString()!;
|
||||
var state = data["state"].ToString()?.ToLower() == "true";
|
||||
|
||||
var voiceState = new TTSVoiceState()
|
||||
{
|
||||
Id = id,
|
||||
Id = voiceId,
|
||||
UserId = channel.Id,
|
||||
Enabled = state,
|
||||
};
|
||||
|
||||
var result = channel.VoiceStates.Set(id, voiceState);
|
||||
var result = channel.VoiceStates.Set(voiceId, voiceState);
|
||||
if (result)
|
||||
{
|
||||
_logger.Information($"Updated voice state on channel [voice id: {id}][state: {state}][channel: {channel.Id}]");
|
||||
_logger.Information($"Updated voice state on channel [voice id: {voiceId}][state: {state}][channel: {channel.Id}]");
|
||||
return Task.FromResult(RequestResult.Successful(voiceState));
|
||||
}
|
||||
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the database."));
|
||||
|
||||
98
Server.cs
98
Server.cs
@@ -2,6 +2,7 @@ using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using CommonSocketLibrary.Common;
|
||||
using HermesSocketLibrary.Requests.Messages;
|
||||
using HermesSocketLibrary.Socket.Data;
|
||||
using HermesSocketServer.Socket;
|
||||
using ILogger = Serilog.ILogger;
|
||||
@@ -32,7 +33,7 @@ namespace HermesSocketLibrary
|
||||
|
||||
public async Task Handle(WebSocketUser socket, HttpContext context)
|
||||
{
|
||||
_logger.Information($"Socket connected [ip: {socket.IPAddress}][uid: {socket.UID}]");
|
||||
_logger.Information($"Socket connected [ip: {socket.IPAddress}][uid: {socket.SessionId}]");
|
||||
_sockets.Add(socket);
|
||||
var buffer = new byte[1024 * 8];
|
||||
|
||||
@@ -44,70 +45,71 @@ namespace HermesSocketLibrary
|
||||
if (result == null || result.MessageType == WebSocketMessageType.Close || !socket.Connected)
|
||||
break;
|
||||
|
||||
string message = Encoding.UTF8.GetString(buffer, 0, result.Count).TrimEnd('\0');
|
||||
var obj = JsonSerializer.Deserialize<WebSocketMessage>(message, _options);
|
||||
if (obj == null)
|
||||
string messageString = Encoding.UTF8.GetString(buffer, 0, result.Count).TrimEnd('\0');
|
||||
var message = JsonSerializer.Deserialize<WebSocketMessage>(messageString, _options);
|
||||
if (message == null)
|
||||
continue;
|
||||
|
||||
if (obj.OpCode != 0)
|
||||
_logger.Information($"rxm: {message} [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.UID}]");
|
||||
if (message.OpCode != 0)
|
||||
_logger.Information($"rxm: {messageString} [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.SessionId}]");
|
||||
|
||||
int[] nonProtectedOps = { 0, 1 };
|
||||
if (string.IsNullOrEmpty(socket.Id) && !nonProtectedOps.Contains(obj.OpCode))
|
||||
if (message.OpCode < 0 || message.OpCode > 8 || message.OpCode == 2 || message.OpCode == 4)
|
||||
{
|
||||
_logger.Warning($"An attempt was made to use protected routes while not logged in [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.UID}]");
|
||||
await socket.Send(5, new LoggingMessage("Received an invalid message: " + messageString, HermesLoggingLevel.Error));
|
||||
return;
|
||||
}
|
||||
|
||||
bool loggedIn = !string.IsNullOrEmpty(socket.Id);
|
||||
int[] nonProtectedOps = { 0, 1 };
|
||||
if (!loggedIn && !nonProtectedOps.Contains(message.OpCode))
|
||||
{
|
||||
_logger.Warning($"An attempt was made to use protected routes while not logged in [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.SessionId}]");
|
||||
return;
|
||||
}
|
||||
int[] protectedOps = { 0, 3, 5, 6, 7, 8 };
|
||||
if (!string.IsNullOrEmpty(socket.Id) && !protectedOps.Contains(obj.OpCode))
|
||||
if (loggedIn && !protectedOps.Contains(message.OpCode))
|
||||
{
|
||||
_logger.Warning($"An attempt was made to use non-protected routes while logged in [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.UID}]");
|
||||
_logger.Warning($"An attempt was made to use non-protected routes while logged in [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.SessionId}]");
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* 0: Heartbeat
|
||||
* 1: Login RX
|
||||
* 2: Login Ack TX
|
||||
* 3: Request RX
|
||||
* 4: Request Ack TX
|
||||
* 5: Logging RX/TX
|
||||
*/
|
||||
if (obj.Data == null)
|
||||
if (message.Data == null)
|
||||
{
|
||||
await socket.Send(5, new LoggingMessage("Received no data in the message.", HermesLoggingLevel.Warn));
|
||||
continue;
|
||||
}
|
||||
|
||||
string data = obj.Data.ToString()!;
|
||||
if (obj.OpCode == 0)
|
||||
obj.Data = JsonSerializer.Deserialize<HeartbeatMessage>(data, _options);
|
||||
else if (obj.OpCode == 1)
|
||||
obj.Data = JsonSerializer.Deserialize<HermesLoginMessage>(data, _options);
|
||||
else if (obj.OpCode == 3)
|
||||
obj.Data = JsonSerializer.Deserialize<RequestMessage>(data, _options);
|
||||
else if (obj.OpCode == 5)
|
||||
obj.Data = JsonSerializer.Deserialize<LoggingMessage>(data, _options);
|
||||
else if (obj.OpCode == 6)
|
||||
obj.Data = JsonSerializer.Deserialize<ChatterMessage>(data, _options);
|
||||
else if (obj.OpCode == 7)
|
||||
obj.Data = JsonSerializer.Deserialize<EmoteDetailsMessage>(data, _options);
|
||||
else if (obj.OpCode == 8)
|
||||
obj.Data = JsonSerializer.Deserialize<EmoteUsageMessage>(data, _options);
|
||||
|
||||
string data = message.Data.ToString()!;
|
||||
if (message.OpCode == 0)
|
||||
message.Data = JsonSerializer.Deserialize<HeartbeatMessage>(data, _options);
|
||||
else if (message.OpCode == 1)
|
||||
message.Data = JsonSerializer.Deserialize<HermesLoginMessage>(data, _options);
|
||||
else if (message.OpCode == 3)
|
||||
message.Data = JsonSerializer.Deserialize<RequestMessage>(data, _options);
|
||||
else if (message.OpCode == 5)
|
||||
message.Data = JsonSerializer.Deserialize<LoggingMessage>(data, _options);
|
||||
else if (message.OpCode == 6)
|
||||
message.Data = JsonSerializer.Deserialize<ChatterMessage>(data, _options);
|
||||
else if (message.OpCode == 7)
|
||||
message.Data = JsonSerializer.Deserialize<EmoteDetailsMessage>(data, _options);
|
||||
else if (message.OpCode == 8)
|
||||
message.Data = JsonSerializer.Deserialize<EmoteUsageMessage>(data, _options);
|
||||
//else if (message.OpCode == 9)
|
||||
// message.Data = JsonSerializer.Deserialize<SlaveMessage>(data, _options);
|
||||
else
|
||||
{
|
||||
await socket.Send(5, new LoggingMessage("Received an invalid message: " + message, HermesLoggingLevel.Error));
|
||||
await socket.Send(5, new LoggingMessage("Received a message with invalid data: " + messageString, HermesLoggingLevel.Error));
|
||||
continue;
|
||||
}
|
||||
await _handlers.Execute(socket, obj.OpCode, obj.Data);
|
||||
await _handlers.Execute(socket, message.OpCode, message.Data);
|
||||
}
|
||||
catch (WebSocketException wse)
|
||||
{
|
||||
_logger.Error(wse, $"Error trying to process a socket message [code: {wse.ErrorCode}][ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.UID}]");
|
||||
_logger.Error(wse, $"Error trying to process a socket message [code: {wse.ErrorCode}][ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.SessionId}]");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, $"Error trying to process a socket message [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.UID}]");
|
||||
_logger.Error(e, $"Error trying to process a socket message [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.SessionId}]");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,14 +120,26 @@ namespace HermesSocketLibrary
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Information(e, $"Client failed to disconnect [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.UID}]");
|
||||
_logger.Information(e, $"Client failed to disconnect [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.SessionId}]");
|
||||
}
|
||||
finally
|
||||
{
|
||||
socket.Dispose();
|
||||
_sockets.Remove(socket);
|
||||
}
|
||||
_logger.Information($"Client disconnected [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.UID}]");
|
||||
_logger.Information($"Client disconnected [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.SessionId}]");
|
||||
|
||||
// Update slave status of another client from the same user if available.
|
||||
// TODO: Ensure one of the clients is always a non-slave.
|
||||
if (socket.Id != null && !socket.Slave)
|
||||
{
|
||||
var client = _sockets.GetSockets(socket.Id).Where(s => !s.WebLogin).FirstOrDefault();
|
||||
if (client != null)
|
||||
{
|
||||
await client.Send(9, new SlaveMessage() { Slave = false });
|
||||
client.Slave = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
using System.Collections.Concurrent;
|
||||
using HermesSocketLibrary.db;
|
||||
using HermesSocketLibrary.Requests.Messages;
|
||||
using HermesSocketServer.Models;
|
||||
using HermesSocketServer.Store;
|
||||
using HermesSocketServer.Validators;
|
||||
|
||||
namespace HermesSocketServer.Services
|
||||
{
|
||||
@@ -10,15 +10,17 @@ namespace HermesSocketServer.Services
|
||||
{
|
||||
private readonly IStore<string, User> _users;
|
||||
private readonly Database _database;
|
||||
private readonly IStore<string, TTSVoice> _voices;
|
||||
private readonly ServerConfiguration _configuration;
|
||||
private readonly Serilog.ILogger _logger;
|
||||
private readonly IDictionary<string, Channel> _channels;
|
||||
private readonly object _lock;
|
||||
|
||||
public ChannelManager(IStore<string, User> users, Database database, ServerConfiguration configuration, Serilog.ILogger logger)
|
||||
public ChannelManager(IStore<string, User> users, Database database, IStore<string, TTSVoice> voices, ServerConfiguration configuration, Serilog.ILogger logger)
|
||||
{
|
||||
_users = users;
|
||||
_database = database;
|
||||
_voices = voices;
|
||||
_configuration = configuration;
|
||||
_logger = logger;
|
||||
_channels = new ConcurrentDictionary<string, Channel>();
|
||||
@@ -26,68 +28,74 @@ namespace HermesSocketServer.Services
|
||||
}
|
||||
|
||||
|
||||
public Task<Channel?> Add(string userId)
|
||||
public async Task<Channel?> Add(string userId)
|
||||
{
|
||||
var user = _users.Get(userId);
|
||||
if (user == null)
|
||||
return Task.FromResult<Channel?>(null);
|
||||
return null;
|
||||
|
||||
lock (_lock)
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
if (_channels.ContainsKey(userId))
|
||||
return Task.FromResult<Channel?>(null);
|
||||
|
||||
var actionTable = _configuration.Database.Tables["Action"];
|
||||
var chatterTable = _configuration.Database.Tables["Chatter"];
|
||||
var connectionTable = _configuration.Database.Tables["Connection"];
|
||||
//var chatterGroupTable = _configuration.Database.Tables["ChatterGroup"];
|
||||
var groupTable = _configuration.Database.Tables["Group"];
|
||||
var groupPermissionTable = _configuration.Database.Tables["GroupPermission"];
|
||||
var policyTable = _configuration.Database.Tables["Policy"];
|
||||
var redemptionTable = _configuration.Database.Tables["Redemption"];
|
||||
var ttsFilterTable = _configuration.Database.Tables["TtsFilter"];
|
||||
var ttsVoiceStateTable = _configuration.Database.Tables["VoiceState"];
|
||||
|
||||
var chatters = new ChatterStore(userId, chatterTable, _database, _logger);
|
||||
var connections = new ConnectionStore(userId, connectionTable, _database, _logger);
|
||||
var groups = new GroupStore(userId, groupTable, _database, _configuration, _logger);
|
||||
var groupPermissions = new GroupPermissionStore(userId, groupPermissionTable, _database, _logger);
|
||||
var policies = new PolicyStore(userId, policyTable, _database, _logger);
|
||||
var filters = new TTSFilterStore(userId, ttsFilterTable, _database, _logger);
|
||||
var actions = new ActionStore(userId, actionTable, _database, _logger);
|
||||
var redemptions = new RedemptionStore(userId, redemptionTable, _database, _logger);
|
||||
var voiceStates = new VoiceStateStore(userId, new VoiceIdValidator(), ttsVoiceStateTable, _database, _logger);
|
||||
|
||||
Task.WaitAll([
|
||||
chatters.Load(),
|
||||
connections.Load(),
|
||||
groups.Load(),
|
||||
groupPermissions.Load(),
|
||||
policies.Load(),
|
||||
filters.Load(),
|
||||
actions.Load(),
|
||||
redemptions.Load(),
|
||||
voiceStates.Save(),
|
||||
]);
|
||||
|
||||
var channel = new Channel()
|
||||
lock (_lock)
|
||||
{
|
||||
Id = userId,
|
||||
User = user,
|
||||
Chatters = chatters,
|
||||
Connections = connections,
|
||||
Groups = groups,
|
||||
GroupPermissions = groupPermissions,
|
||||
Policies = policies,
|
||||
Filters = filters,
|
||||
Actions = actions,
|
||||
Redemptions = redemptions,
|
||||
VoiceStates = voiceStates,
|
||||
};
|
||||
if (_channels.TryGetValue(userId, out var channel))
|
||||
return Task.FromResult<Channel?>(channel);
|
||||
|
||||
_channels.Add(userId, channel);
|
||||
return Task.FromResult<Channel?>(channel);
|
||||
}
|
||||
var actionTable = _configuration.Database.Tables["Action"];
|
||||
var chatterTable = _configuration.Database.Tables["Chatter"];
|
||||
var connectionTable = _configuration.Database.Tables["Connection"];
|
||||
//var chatterGroupTable = _configuration.Database.Tables["ChatterGroup"];
|
||||
var groupTable = _configuration.Database.Tables["Group"];
|
||||
var groupPermissionTable = _configuration.Database.Tables["GroupPermission"];
|
||||
var policyTable = _configuration.Database.Tables["Policy"];
|
||||
var redemptionTable = _configuration.Database.Tables["Redemption"];
|
||||
var ttsFilterTable = _configuration.Database.Tables["TtsFilter"];
|
||||
var ttsVoiceStateTable = _configuration.Database.Tables["VoiceState"];
|
||||
|
||||
var chatters = new ChatterStore(userId, chatterTable, _database, _logger);
|
||||
var connections = new ConnectionStore(userId, connectionTable, _database, _logger);
|
||||
var groups = new GroupStore(userId, groupTable, _database, _configuration, _logger);
|
||||
var groupPermissions = new GroupPermissionStore(userId, groupPermissionTable, groups, _database, _logger);
|
||||
var policies = new PolicyStore(userId, policyTable, groups, _database, _logger);
|
||||
var filters = new TTSFilterStore(userId, ttsFilterTable, _database, _logger);
|
||||
var actions = new ActionStore(userId, actionTable, _database, _logger);
|
||||
var redemptions = new RedemptionStore(userId, redemptionTable, actions, _database, _logger);
|
||||
var voiceStates = new VoiceStateStore(userId, ttsVoiceStateTable, _voices, _database, _logger);
|
||||
|
||||
channel = new Channel()
|
||||
{
|
||||
Id = userId,
|
||||
User = user,
|
||||
Chatters = chatters,
|
||||
Connections = connections,
|
||||
Groups = groups,
|
||||
GroupPermissions = groupPermissions,
|
||||
Policies = policies,
|
||||
Filters = filters,
|
||||
Actions = actions,
|
||||
Redemptions = redemptions,
|
||||
VoiceStates = voiceStates,
|
||||
};
|
||||
|
||||
Task.WaitAll([
|
||||
channel.Actions.Load(),
|
||||
channel.Chatters.Load(),
|
||||
channel.Connections.Load(),
|
||||
channel.Groups.Load(),
|
||||
channel.Filters.Load(),
|
||||
channel.VoiceStates.Load(),
|
||||
]);
|
||||
|
||||
Task.WaitAll([
|
||||
channel.GroupPermissions.Load(),
|
||||
channel.Policies.Load(),
|
||||
channel.Redemptions.Load(),
|
||||
]);
|
||||
|
||||
_channels.Add(userId, channel);
|
||||
return Task.FromResult<Channel?>(channel);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Channel? Get(string channelId)
|
||||
@@ -121,17 +129,25 @@ namespace HermesSocketServer.Services
|
||||
foreach (var channel in _channels.Values)
|
||||
{
|
||||
_logger.Debug($"Saving channel data to database [channel id: {channel.Id}][channel name: {channel.User.Name}]");
|
||||
await Task.WhenAll([
|
||||
var genericTablesTask = Task.WhenAll([
|
||||
channel.Chatters.Save(),
|
||||
channel.Connections.Save(),
|
||||
channel.Filters.Save(),
|
||||
channel.VoiceStates.Save(),
|
||||
]).ConfigureAwait(false);
|
||||
|
||||
await Task.WhenAll([
|
||||
channel.Actions.Save(),
|
||||
channel.Groups.Save(),
|
||||
]).ConfigureAwait(false);
|
||||
|
||||
await Task.WhenAll([
|
||||
channel.GroupPermissions.Save(),
|
||||
channel.Policies.Save(),
|
||||
channel.Filters.Save(),
|
||||
channel.Actions.Save(),
|
||||
channel.Redemptions.Save(),
|
||||
channel.VoiceStates.Save(),
|
||||
]);
|
||||
]).ConfigureAwait(false);
|
||||
|
||||
await genericTablesTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using HermesSocketLibrary.db;
|
||||
using HermesSocketLibrary.Requests.Messages;
|
||||
using HermesSocketServer.Models;
|
||||
using HermesSocketServer.Store;
|
||||
@@ -24,10 +23,10 @@ namespace HermesSocketServer.Services
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.Information("Loading TTS voices...");
|
||||
await _voices.Load();
|
||||
_logger.Information("Loading users...");
|
||||
await _users.Load();
|
||||
_logger.Information("Loading TTS voices...");
|
||||
await _voices.Load();
|
||||
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
@@ -35,11 +34,10 @@ namespace HermesSocketServer.Services
|
||||
|
||||
while (true)
|
||||
{
|
||||
await Task.WhenAll([
|
||||
_voices.Save(),
|
||||
_users.Save(),
|
||||
_channels.Save(),
|
||||
]);
|
||||
await _users.Save();
|
||||
await _voices.Save();
|
||||
await _channels.Save();
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(_configuration.Database.SaveDelayInSeconds));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -45,16 +45,24 @@ namespace HermesSocketServer.Socket.Handlers
|
||||
if (userId == null)
|
||||
return;
|
||||
|
||||
IEnumerable<WebSocketUser?> recipients = Enumerable.Empty<WebSocketUser?>();
|
||||
lock (_lock)
|
||||
{
|
||||
if (sender.Id != null)
|
||||
return;
|
||||
throw new Exception("User already logged in.");
|
||||
|
||||
sender.Id = userId;
|
||||
sender.ApiKey = data.ApiKey;
|
||||
sender.WebLogin = data.WebLogin;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(sender.Id))
|
||||
throw new Exception("Credentials do not match.");
|
||||
|
||||
recipients = _sockets.GetSockets(userId).ToList().Where(s => s.SessionId != sender.SessionId);
|
||||
sender.Slave = data.WebLogin || recipients.Where(r => r?.WebLogin != true).Any();
|
||||
}
|
||||
|
||||
sender.ApiKey = data.ApiKey;
|
||||
sender.WebLogin = data.WebLogin;
|
||||
|
||||
var channel = _manager.Get(userId);
|
||||
if (channel == null)
|
||||
{
|
||||
@@ -73,11 +81,12 @@ namespace HermesSocketServer.Socket.Handlers
|
||||
}
|
||||
if (string.IsNullOrEmpty(channel.User.DefaultVoice))
|
||||
_logger.Warning($"No default voice was set for an user [user id: {userId}][api key: {data.ApiKey}]");
|
||||
|
||||
|
||||
sql = "select \"providerAccountId\" from \"Account\" where \"userId\" = @user and provider = @provider";
|
||||
var result2 = await _database.ExecuteScalar(sql, new Dictionary<string, object>() { { "user", userId }, { "provider", "twitch" } });
|
||||
var providerId = result2?.ToString();
|
||||
if (providerId == null) {
|
||||
if (providerId == null)
|
||||
{
|
||||
_logger.Warning($"Could not find the Provider Account Id [user id: {userId}][provider: twitch]");
|
||||
return;
|
||||
}
|
||||
@@ -86,7 +95,7 @@ namespace HermesSocketServer.Socket.Handlers
|
||||
{
|
||||
UserId = userId,
|
||||
ProviderAccountId = providerId,
|
||||
SessionId = sender.UID,
|
||||
SessionId = sender.SessionId,
|
||||
UserName = channel.User.Name,
|
||||
OwnerId = _configuration.Tts.OwnerId,
|
||||
Admin = sender.Admin,
|
||||
@@ -94,6 +103,7 @@ namespace HermesSocketServer.Socket.Handlers
|
||||
WordFilters = channel.Filters.Get().Values,
|
||||
DefaultTTSVoice = channel.User.DefaultVoice ?? _configuration.Tts.DefaultTtsVoice,
|
||||
TTSVoicesAvailable = _voices.Get().ToDictionary(v => v.Key, v => v.Value.Name),
|
||||
Slave = sender.Slave,
|
||||
};
|
||||
|
||||
var userIdDict = new Dictionary<string, object>() { { "user", userId } };
|
||||
@@ -122,7 +132,7 @@ namespace HermesSocketServer.Socket.Handlers
|
||||
|
||||
await sender.Send(2, ack);
|
||||
|
||||
string version = data.MajorVersion == null ? "unknown" : $"{data.MajorVersion}.{data.MinorVersion}";
|
||||
string version = $"{data.MajorVersion}.{data.MinorVersion}.{data.PatchVersion}";
|
||||
_logger.Information($"Hermes client logged in {(sender.Admin ? "as administrator " : "")}[name: {sender.Name}][id: {userId}][ip: {sender.IPAddress}][version: {version}][web: {data.WebLogin}]");
|
||||
|
||||
ack = new LoginAckMessage()
|
||||
@@ -133,7 +143,6 @@ namespace HermesSocketServer.Socket.Handlers
|
||||
WebLogin = data.WebLogin
|
||||
};
|
||||
|
||||
var recipients = _sockets.GetSockets(userId).ToList().Where(s => s.UID != sender.UID);
|
||||
var tasks = new List<Task>();
|
||||
foreach (var socket in recipients)
|
||||
{
|
||||
|
||||
@@ -38,7 +38,7 @@ namespace HermesSocketServer.Socket.Handlers
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
logging.Invoke(message.Exception, message.Message + $" [ip: {sender.IPAddress}][id: {sender.Id}][name: {sender.Name}][token: {sender.ApiKey}][uid: {sender.UID}]");
|
||||
logging.Invoke(message.Exception, message.Message + $" [ip: {sender.IPAddress}][id: {sender.Id}][name: {sender.Name}][token: {sender.ApiKey}][uid: {sender.SessionId}]");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,10 @@ namespace HermesSocketServer.Socket
|
||||
{
|
||||
public class HermesSocketManager
|
||||
{
|
||||
private IList<WebSocketUser> _sockets;
|
||||
private System.Timers.Timer _timer;
|
||||
private ILogger _logger;
|
||||
private readonly IList<WebSocketUser> _sockets;
|
||||
private readonly System.Timers.Timer _timer;
|
||||
private readonly ILogger _logger;
|
||||
private readonly object _lock = new object();
|
||||
|
||||
|
||||
public HermesSocketManager(ILogger logger)
|
||||
@@ -18,31 +19,40 @@ namespace HermesSocketServer.Socket
|
||||
_timer.Elapsed += async (sender, e) => await HandleHeartbeats(e);
|
||||
_timer.Enabled = true;
|
||||
_logger = logger;
|
||||
_lock = new object();
|
||||
}
|
||||
|
||||
|
||||
public void Add(WebSocketUser socket)
|
||||
{
|
||||
_sockets.Add(socket);
|
||||
lock (_lock)
|
||||
{
|
||||
_sockets.Add(socket);
|
||||
}
|
||||
}
|
||||
|
||||
public IList<WebSocketUser> GetAllSockets()
|
||||
{
|
||||
return _sockets.AsReadOnly();
|
||||
lock (_lock)
|
||||
{
|
||||
return _sockets.AsReadOnly();
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<WebSocketUser> GetSockets(string userId)
|
||||
{
|
||||
foreach (var socket in _sockets)
|
||||
lock (_lock)
|
||||
{
|
||||
if (socket.Id == userId)
|
||||
yield return socket;
|
||||
return _sockets.Where(s => s.Id == userId);
|
||||
}
|
||||
}
|
||||
|
||||
public bool Remove(WebSocketUser socket)
|
||||
{
|
||||
return _sockets.Remove(socket);
|
||||
lock (_lock)
|
||||
{
|
||||
return _sockets.Remove(socket);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleHeartbeats(ElapsedEventArgs e)
|
||||
|
||||
@@ -22,7 +22,8 @@ namespace HermesSocketServer.Socket
|
||||
public WebSocketState State { get => _socket.State; }
|
||||
public IPAddress? IPAddress { get => _ipAddress; }
|
||||
public bool Connected { get => _connected; }
|
||||
public string UID { get; }
|
||||
public bool Slave { get; set; }
|
||||
public string SessionId { get; }
|
||||
public string? ApiKey { get; set; }
|
||||
public string? Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
@@ -43,7 +44,7 @@ namespace HermesSocketServer.Socket
|
||||
Admin = false;
|
||||
WebLogin = false;
|
||||
_cts = new CancellationTokenSource();
|
||||
UID = Guid.NewGuid().ToString("D");
|
||||
SessionId = Guid.NewGuid().ToString("D");
|
||||
LastHeartbeatReceived = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
|
||||
@@ -118,6 +118,8 @@ s.AddSingleton<IRequest, GetConnections>();
|
||||
s.AddSingleton<IRequest, GetDefaultTTSVoice>();
|
||||
s.AddSingleton<IRequest, GetEmotes>();
|
||||
s.AddSingleton<IRequest, GetEnabledTTSVoices>();
|
||||
s.AddSingleton<IRequest, GetGroups>();
|
||||
s.AddSingleton<IRequest, GetGroupPermissions>();
|
||||
s.AddSingleton<IRequest, GetPermissions>();
|
||||
s.AddSingleton<IRequest, GetRedeemableActions>();
|
||||
s.AddSingleton<IRequest, GetRedemptions>();
|
||||
|
||||
@@ -23,7 +23,7 @@ namespace HermesSocketServer.Store
|
||||
public override async Task Load()
|
||||
{
|
||||
var data = new Dictionary<string, object>() { { "user", _userId } };
|
||||
string sql = $"SELECT name, type, data FROM \"Action\" WHERE \"userId\" = @user";
|
||||
string sql = $"SELECT name, type, has_message, data FROM \"Action\" WHERE \"userId\" = @user";
|
||||
await _database.Execute(sql, data, (reader) =>
|
||||
{
|
||||
var name = reader.GetString(0);
|
||||
@@ -32,7 +32,8 @@ namespace HermesSocketServer.Store
|
||||
UserId = _userId,
|
||||
Name = name,
|
||||
Type = reader.GetString(1),
|
||||
Data = JsonSerializer.Deserialize<IDictionary<string, string>>(reader.GetString(2))!
|
||||
HasMessage = reader.GetBoolean(2),
|
||||
Data = JsonSerializer.Deserialize<IDictionary<string, string>>(reader.GetString(3))!
|
||||
});
|
||||
});
|
||||
_logger.Information($"Loaded {_store.Count} redeemable actions from database.");
|
||||
@@ -46,6 +47,9 @@ namespace HermesSocketServer.Store
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value.Name, nameof(value.Name));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value.Type, nameof(value.Type));
|
||||
ArgumentNullException.ThrowIfNull(value.Data, nameof(value.Data));
|
||||
|
||||
if (value.Name.Length > 36)
|
||||
throw new ArgumentException("Action name cannot be longer than 36 characters.");
|
||||
}
|
||||
|
||||
protected override void OnInitialModify(string key, RedeemableAction oldValue, RedeemableAction newValue)
|
||||
|
||||
@@ -54,6 +54,9 @@ namespace HermesSocketServer.Store
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value.Scope, nameof(value.Scope));
|
||||
ArgumentNullException.ThrowIfNull(value.ExpiresAt, nameof(value.ExpiresAt));
|
||||
ArgumentNullException.ThrowIfNull(value.Default, nameof(value.Default));
|
||||
|
||||
if (value.Name.Length > 36)
|
||||
throw new ArgumentException("Action name cannot be longer than 36 characters.");
|
||||
}
|
||||
|
||||
protected override void OnInitialModify(string key, Connection oldValue, Connection newValue)
|
||||
@@ -70,6 +73,8 @@ namespace HermesSocketServer.Store
|
||||
ArgumentNullException.ThrowIfNull(newValue.Default, nameof(newValue.Default));
|
||||
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.UserId, newValue.UserId, nameof(oldValue.UserId));
|
||||
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.Name, newValue.Name, nameof(oldValue.Name));
|
||||
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.Type, newValue.Type, nameof(oldValue.Type));
|
||||
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.ClientId, newValue.ClientId, nameof(oldValue.ClientId));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,16 @@ namespace HermesSocketServer.Store
|
||||
public class GroupPermissionStore : AutoSavedStore<string, GroupPermission>
|
||||
{
|
||||
private readonly string _userId;
|
||||
private readonly IStore<string, Group> _groups;
|
||||
private readonly Database _database;
|
||||
private readonly Serilog.ILogger _logger;
|
||||
|
||||
|
||||
public GroupPermissionStore(string userId, DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||
public GroupPermissionStore(string userId, DatabaseTable table, IStore<string, Group> groups, Database database, Serilog.ILogger logger)
|
||||
: base(table, database, logger)
|
||||
{
|
||||
_userId = userId;
|
||||
_groups = groups;
|
||||
_database = database;
|
||||
_logger = logger;
|
||||
}
|
||||
@@ -30,7 +32,7 @@ namespace HermesSocketServer.Store
|
||||
{
|
||||
Id = id,
|
||||
UserId = _userId,
|
||||
GroupId = reader.GetGuid(1).ToString(),
|
||||
GroupId = reader.GetGuid(1),
|
||||
Path = reader.GetString(2),
|
||||
Allow = await reader.IsDBNullAsync(3) ? null : reader.GetBoolean(3),
|
||||
});
|
||||
@@ -43,18 +45,26 @@ namespace HermesSocketServer.Store
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value.UserId, nameof(value.UserId));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value.GroupId, nameof(value.GroupId));
|
||||
ArgumentNullException.ThrowIfNull(value.GroupId, nameof(value.GroupId));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value.Path, nameof(value.Path));
|
||||
|
||||
if (value.Path.Length > 100)
|
||||
throw new ArgumentException("The path cannot be longer than 100 characters.");
|
||||
if (_groups.Get(value.GroupId.ToString()) == null)
|
||||
throw new ArgumentException("The group id does not exist.");
|
||||
}
|
||||
|
||||
protected override void OnInitialModify(string key, GroupPermission oldValue, GroupPermission newValue)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(newValue, nameof(newValue));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.UserId, nameof(newValue.UserId));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.GroupId, nameof(newValue.GroupId));
|
||||
ArgumentNullException.ThrowIfNull(newValue.GroupId, nameof(newValue.GroupId));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.Path, nameof(newValue.Path));
|
||||
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.UserId, newValue.UserId, nameof(oldValue.UserId));
|
||||
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.GroupId, newValue.GroupId, nameof(oldValue.GroupId));
|
||||
|
||||
if (oldValue.Path != newValue.Path && newValue.Path.Length > 100)
|
||||
throw new ArgumentException("The path cannot be longer than 100 characters.");
|
||||
}
|
||||
|
||||
protected override void OnPostRemove(string key, GroupPermission value)
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace HermesSocketServer.Store
|
||||
Task Load();
|
||||
bool Modify(K? key, Action<V> modify);
|
||||
bool Modify(K? key, V value);
|
||||
bool Remove(K? key);
|
||||
bool Remove(K? key, bool fromCascade = false);
|
||||
Task Save();
|
||||
bool Set(K? key, V value);
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ namespace HermesSocketServer.Store.Internal
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool Remove(K? key)
|
||||
public bool Remove(K? key, bool fromCascade = false)
|
||||
{
|
||||
if (key == null)
|
||||
return false;
|
||||
@@ -102,7 +102,7 @@ namespace HermesSocketServer.Store.Internal
|
||||
if (!_added.Remove(key))
|
||||
{
|
||||
_modified.Remove(key);
|
||||
if (!_deleted.Contains(key))
|
||||
if (!fromCascade && !_deleted.Contains(key))
|
||||
{
|
||||
_deleted.Add(key);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using HermesSocketLibrary.db;
|
||||
using HermesSocketLibrary.Requests.Messages;
|
||||
using HermesSocketServer.Messages;
|
||||
using HermesSocketServer.Store.Internal;
|
||||
|
||||
@@ -7,14 +8,16 @@ namespace HermesSocketServer.Store
|
||||
public class PolicyStore : AutoSavedStore<string, Policy>
|
||||
{
|
||||
private readonly string _userId;
|
||||
private readonly IStore<string, Group> _groups;
|
||||
private readonly Database _database;
|
||||
private readonly Serilog.ILogger _logger;
|
||||
|
||||
|
||||
public PolicyStore(string userId, DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||
public PolicyStore(string userId, DatabaseTable table, IStore<string, Group> groups, Database database, Serilog.ILogger logger)
|
||||
: base(table, database, logger)
|
||||
{
|
||||
_userId = userId;
|
||||
_groups = groups;
|
||||
_database = database;
|
||||
_logger = logger;
|
||||
}
|
||||
@@ -50,6 +53,9 @@ namespace HermesSocketServer.Store
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value.Span, nameof(value.Span));
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(value.Span, 1000, nameof(value.Span));
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(value.Span, 86400, nameof(value.Span));
|
||||
|
||||
if (_groups.Get(value.GroupId.ToString()) == null)
|
||||
throw new ArgumentException("The group id does not exist.");
|
||||
}
|
||||
|
||||
protected override void OnInitialModify(string key, Policy oldValue, Policy newValue)
|
||||
|
||||
@@ -7,14 +7,16 @@ namespace HermesSocketServer.Store
|
||||
public class RedemptionStore : AutoSavedStore<string, Redemption>
|
||||
{
|
||||
private readonly string _userId;
|
||||
private readonly IStore<string, RedeemableAction> _actions;
|
||||
private readonly Database _database;
|
||||
private readonly Serilog.ILogger _logger;
|
||||
|
||||
|
||||
public RedemptionStore(string userId, DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||
public RedemptionStore(string userId, DatabaseTable table, IStore<string, RedeemableAction> actions, Database database, Serilog.ILogger logger)
|
||||
: base(table, database, logger)
|
||||
{
|
||||
_userId = userId;
|
||||
_actions = actions;
|
||||
_database = database;
|
||||
_logger = logger;
|
||||
}
|
||||
@@ -50,6 +52,9 @@ namespace HermesSocketServer.Store
|
||||
ArgumentNullException.ThrowIfNull(value.Order, nameof(value.Order));
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(value.Order, nameof(value.Order));
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(value.Order, 99, nameof(value.Order));
|
||||
|
||||
if (_actions.Get(value.ActionName) == null)
|
||||
throw new ArgumentException("The action name does not exist.");
|
||||
}
|
||||
|
||||
protected override void OnInitialModify(string key, Redemption oldValue, Redemption newValue)
|
||||
@@ -64,6 +69,9 @@ namespace HermesSocketServer.Store
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(newValue.Order, 99, nameof(newValue.Order));
|
||||
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.Id, newValue.Id, nameof(newValue.Id));
|
||||
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.UserId, newValue.UserId, nameof(newValue.UserId));
|
||||
|
||||
if (oldValue.ActionName != newValue.ActionName && _actions.Get(newValue.ActionName) == null)
|
||||
throw new ArgumentException("The action name does not exist.");
|
||||
}
|
||||
|
||||
protected override void OnPostRemove(string key, Redemption? value)
|
||||
|
||||
@@ -8,18 +8,21 @@ namespace HermesSocketServer.Store
|
||||
public class VoiceStateStore : ComplexAutoSavedStore<string, TTSVoiceState>
|
||||
{
|
||||
private readonly string _userId;
|
||||
private readonly IStore<string, TTSVoice> _voices;
|
||||
private readonly VoiceIdValidator _idValidator;
|
||||
private readonly Database _database;
|
||||
private readonly Serilog.ILogger _logger;
|
||||
|
||||
|
||||
public VoiceStateStore(string userId, VoiceIdValidator voiceIdValidator, DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||
public VoiceStateStore(string userId, DatabaseTable table, IStore<string, TTSVoice> voices, Database database, Serilog.ILogger logger)
|
||||
: base(table, database, logger)
|
||||
{
|
||||
_userId = userId;
|
||||
_idValidator = voiceIdValidator;
|
||||
_voices = voices;
|
||||
_database = database;
|
||||
_logger = logger;
|
||||
|
||||
_idValidator = new VoiceIdValidator();
|
||||
}
|
||||
|
||||
public override async Task Load()
|
||||
@@ -47,6 +50,9 @@ namespace HermesSocketServer.Store
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value.Id, nameof(value.Id));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value.UserId, nameof(value.UserId));
|
||||
ArgumentNullException.ThrowIfNull(value.Enabled, nameof(value.Enabled));
|
||||
|
||||
if (_voices.Get(value.Id) == null)
|
||||
throw new ArgumentException("The voice does not exist.");
|
||||
}
|
||||
|
||||
protected override void OnInitialModify(string key, TTSVoiceState oldValue, TTSVoiceState newValue)
|
||||
|
||||
Reference in New Issue
Block a user