Compare commits

..

4 Commits

Author SHA1 Message Date
Tom
21cb5c9453 Added error message to request acks. 2024-12-27 23:33:13 +00:00
Tom
8277ea0154 Changed sender parameter to channel. 2024-12-27 23:31:36 +00:00
Tom
06bfe110bb Fixed multiple issues. 2024-12-27 22:29:54 +00:00
Tom
6176e6f3b9 Added TTS Filter cache. 2024-12-27 22:28:22 +00:00
37 changed files with 387 additions and 168 deletions

View File

@@ -8,5 +8,6 @@ namespace HermesSocketServer.Models
public User User { get; set; } public User User { get; set; }
public ChatterStore Chatters { get; set; } public ChatterStore Chatters { get; set; }
public PolicyStore Policies { get; set; } public PolicyStore Policies { get; set; }
public TTSFilterStore Filters { get; set; }
} }
} }

View File

@@ -1,5 +1,4 @@
using HermesSocketServer.Models; using HermesSocketServer.Models;
using HermesSocketServer.Services;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -8,16 +7,14 @@ namespace HermesSocketServer.Requests
{ {
public string Name => "create_policy"; public string Name => "create_policy";
public string[] RequiredKeys => ["groupId", "path", "count", "span"]; public string[] RequiredKeys => ["groupId", "path", "count", "span"];
private ChannelManager _channels;
private ILogger _logger; private ILogger _logger;
public CreatePolicy(ChannelManager channels, ILogger logger) public CreatePolicy(ILogger logger)
{ {
_channels = channels;
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var id = Guid.NewGuid(); var id = Guid.NewGuid();
string groupId = data["groupId"].ToString()!; string groupId = data["groupId"].ToString()!;
@@ -28,19 +25,17 @@ namespace HermesSocketServer.Requests
var policy = new PolicyMessage() var policy = new PolicyMessage()
{ {
Id = id, Id = id,
UserId = sender, UserId = channel.Id,
GroupId = Guid.Parse(groupId), GroupId = Guid.Parse(groupId),
Path = path, Path = path,
Usage = count, Usage = count,
Span = span, Span = span,
}; };
var channel = _channels.Get(sender);
bool result = channel.Policies.Set(id.ToString(), policy); bool result = channel.Policies.Set(id.ToString(), policy);
if (result) if (result)
{ {
_logger.Information($"Added policy to channel [policy id: {id}][group id: {groupId}][path: {path}][count: {count}][span: {span}][channel: {sender}]"); _logger.Information($"Added policy to channel [policy id: {id}][group id: {groupId}][path: {path}][count: {count}][span: {span}][channel: {channel.Id}]");
return RequestResult.Successful(policy); return RequestResult.Successful(policy);
} }
return RequestResult.Failed("Something went wrong when updating the cache."); return RequestResult.Failed("Something went wrong when updating the cache.");

View File

@@ -0,0 +1,41 @@
using HermesSocketLibrary.Requests.Messages;
using HermesSocketServer.Models;
using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests
{
public class CreateTTSFilter : IRequest
{
public string Name => "create_tts_filter";
public string[] RequiredKeys => ["search", "replace"];
private ILogger _logger;
public CreateTTSFilter(ILogger logger)
{
_logger = logger;
}
public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{
var id = Guid.NewGuid();
string search = data["search"].ToString()!;
string replace = data["replace"].ToString()!;
var filter = new TTSWordFilter()
{
Id = id.ToString(),
UserId = channel.Id,
Search = search,
Replace = replace,
};
bool result = channel.Filters.Set(id.ToString(), filter);
if (result)
{
_logger.Information($"Added filter to channel [filter id: {id}][search: {search}][replace: {replace}][channel: {channel.Id}]");
return RequestResult.Successful(filter);
}
return RequestResult.Failed("Something went wrong when updating the cache.");
}
}
}

View File

@@ -1,6 +1,5 @@
using HermesSocketLibrary.db; using HermesSocketLibrary.db;
using HermesSocketServer.Models; using HermesSocketServer.Models;
using HermesSocketServer.Services;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -9,36 +8,32 @@ namespace HermesSocketServer.Requests
{ {
public string Name => "create_tts_user"; public string Name => "create_tts_user";
public string[] RequiredKeys => ["chatter", "voice"]; public string[] RequiredKeys => ["chatter", "voice"];
private ChannelManager _channels;
private Database _database; private Database _database;
private readonly ServerConfiguration _configuration; private readonly ServerConfiguration _configuration;
private ILogger _logger; private ILogger _logger;
public CreateTTSUser(ChannelManager channels, Database database, ServerConfiguration configuration, ILogger logger) public CreateTTSUser(Database database, ServerConfiguration configuration, ILogger logger)
{ {
_database = database; _database = database;
_channels = channels;
_configuration = configuration; _configuration = configuration;
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
if (long.TryParse(data["chatter"].ToString(), out long chatterId)) if (!long.TryParse(data["chatter"].ToString(), out long chatterId))
data["chatter"] = chatterId;
else
return RequestResult.Failed("Invalid Twitch user id"); return RequestResult.Failed("Invalid Twitch user id");
data["voice"] = data["voice"].ToString(); data["user"] = channel.Id;
data["voice"] = data["voice"].ToString()!;
var check = await _database.ExecuteScalar("SELECT state FROM \"TtsVoiceState\" WHERE \"userId\" = @user AND \"ttsVoiceId\" = @voice", data) ?? false; 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) if ((check is not bool state || !state) && chatterId != _configuration.Tts.OwnerId)
return RequestResult.Failed("Voice is disabled on this channel."); return RequestResult.Failed("Voice is disabled on this channel.");
var channel = _channels.Get(sender);
bool result = channel.Chatters.Set(chatterId.ToString(), new ChatterVoice() bool result = channel.Chatters.Set(chatterId.ToString(), new ChatterVoice()
{ {
UserId = sender, UserId = channel.Id,
ChatterId = chatterId, ChatterId = chatterId,
VoiceId = data["voice"].ToString()! VoiceId = data["voice"].ToString()!
}); });

View File

@@ -19,20 +19,19 @@ namespace HermesSocketServer.Requests
_random = new Random(); _random = new Random();
} }
public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
{ {
data["voice"] = data["voice"].ToString()!; string voice = data["voice"].ToString()!;
string id = RandomString(25); string id = RandomString(25);
var result = _voices.Set(id, new Voice() var result = _voices.Set(id, new Voice()
{ {
Id = id, Id = id,
Name = data["voice"].ToString() Name = voice
}); });
if (result) { if (result) {
_logger.Information($"Added a new voice [voice: {data["voice"]}][voice id: {id}]"); _logger.Information($"Added a new voice [voice: {voice}][voice id: {id}]");
return RequestResult.Successful(id); return RequestResult.Successful(id);
} }
return RequestResult.Failed("Something went wrong when updating the cache."); return RequestResult.Failed("Something went wrong when updating the cache.");

View File

@@ -1,4 +1,4 @@
using HermesSocketServer.Services; using HermesSocketServer.Models;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -7,21 +7,25 @@ namespace HermesSocketServer.Requests
{ {
public string Name => "delete_policy"; public string Name => "delete_policy";
public string[] RequiredKeys => ["id"]; public string[] RequiredKeys => ["id"];
private ChannelManager _channels;
private ILogger _logger; private ILogger _logger;
public DeletePolicy(ChannelManager channels, ILogger logger) public DeletePolicy(ILogger logger)
{ {
_channels = channels;
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var channel = _channels.Get(sender); string policyId = data["id"].ToString()!;
channel.Policies.Remove(data!["id"].ToString()); var policy = channel.Policies.Get(policyId);
if (policy != null) {
channel.Policies.Remove(policyId);
_logger.Information($"Deleted a policy by id [policy id: {data["id"]}]"); _logger.Information($"Deleted a policy by id [policy id: {data["id"]}]");
return RequestResult.Successful(null); return RequestResult.Successful(policy.GroupId + "/" + policy.Path);
}
_logger.Warning("Failed to find policy by id ");
return RequestResult.Failed("Cannot find the policy by id.");
} }
} }
} }

View File

@@ -0,0 +1,26 @@
using HermesSocketServer.Models;
using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests
{
public class DeleteTTSFilter : IRequest
{
public string Name => "delete_tts_filter";
public string[] RequiredKeys => ["id"];
private ILogger _logger;
public DeleteTTSFilter(ILogger logger)
{
_logger = logger;
}
public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{
string filterId = data["id"].ToString()!;
channel.Filters.Remove(filterId);
_logger.Information($"Deleted a TTS filter by id [tts filter id: {filterId}]");
return RequestResult.Successful(null);
}
}
}

View File

@@ -17,10 +17,11 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
_voices.Remove(data!["voice"].ToString()); string voiceId = data["voice"].ToString()!;
_logger.Information($"Deleted a voice by id [voice id: {data["voice"]}]"); _voices.Remove(voiceId);
_logger.Information($"Deleted a voice by id [voice id: {voiceId}]");
return RequestResult.Successful(null); return RequestResult.Successful(null);
} }
} }

View File

@@ -1,4 +1,4 @@
using HermesSocketLibrary.db; using HermesSocketServer.Models;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -7,21 +7,17 @@ namespace HermesSocketServer.Requests
{ {
public string Name => "get_chatter_ids"; public string Name => "get_chatter_ids";
public string[] RequiredKeys => []; public string[] RequiredKeys => [];
private Database _database;
private ILogger _logger; private ILogger _logger;
public GetChatterIds(Database database, ILogger logger) public GetChatterIds(ILogger logger)
{ {
_database = database;
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
IList<long> ids = new List<long>(); IEnumerable<long> ids = channel.Chatters.Get().Values.Select(c => c.ChatterId);
string sql = $"SELECT id FROM \"Chatter\""; _logger.Information($"Fetched all chatters for channel [channel: {channel.Id}]");
await _database.Execute(sql, (IDictionary<string, object>?) null, (r) => ids.Add(r.GetInt64(0)));
_logger.Information($"Fetched all chatters for channel [channel: {sender}]");
return RequestResult.Successful(ids, notifyClientsOnAccount: false); return RequestResult.Successful(ids, notifyClientsOnAccount: false);
} }
} }

View File

@@ -1,5 +1,7 @@
using HermesSocketLibrary.db; using HermesSocketLibrary.db;
using HermesSocketLibrary.Socket.Data; using HermesSocketLibrary.Socket.Data;
using HermesSocketServer.Models;
using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
{ {
@@ -8,17 +10,17 @@ namespace HermesSocketServer.Requests
public string Name => "get_connections"; public string Name => "get_connections";
public string[] RequiredKeys => []; public string[] RequiredKeys => [];
private Database _database; private Database _database;
private Serilog.ILogger _logger; private ILogger _logger;
public GetConnections(Database database, Serilog.ILogger logger) public GetConnections(Database database, ILogger logger)
{ {
_database = database; _database = database;
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var temp = new Dictionary<string, object>() { { "user", sender } }; var temp = new Dictionary<string, object>() { { "user", channel.Id } };
var connections = new List<Connection>(); var connections = new List<Connection>();
string sql = "select \"name\", \"type\", \"clientId\", \"accessToken\", \"grantType\", \"scope\", \"expiresAt\", \"default\" from \"Connection\" where \"userId\" = @user"; string sql = "select \"name\", \"type\", \"clientId\", \"accessToken\", \"grantType\", \"scope\", \"expiresAt\", \"default\" from \"Connection\" where \"userId\" = @user";

View File

@@ -1,3 +1,4 @@
using HermesSocketServer.Models;
using HermesSocketServer.Store; using HermesSocketServer.Store;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
@@ -18,9 +19,9 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var user = _users.Get(sender); var user = _users.Get(channel.Id);
if (user == null) if (user == null)
return RequestResult.Failed("Unable to find user data.", notifyClientsOnAccount: false); return RequestResult.Failed("Unable to find user data.", notifyClientsOnAccount: false);

View File

@@ -1,5 +1,6 @@
using HermesSocketLibrary.db; using HermesSocketLibrary.db;
using HermesSocketLibrary.Requests.Messages; using HermesSocketLibrary.Requests.Messages;
using HermesSocketServer.Models;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -17,7 +18,7 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
IList<EmoteInfo> emotes = new List<EmoteInfo>(); IList<EmoteInfo> emotes = new List<EmoteInfo>();
string sql = $"SELECT id, name FROM \"Emote\""; string sql = $"SELECT id, name FROM \"Emote\"";
@@ -26,7 +27,7 @@ namespace HermesSocketServer.Requests
Id = r.GetString(0), Id = r.GetString(0),
Name = r.GetString(1) Name = r.GetString(1)
})); }));
_logger.Information($"Fetched all emotes for channel [channel: {sender}]"); _logger.Information($"Fetched all emotes for channel [channel: {channel.Id}]");
return RequestResult.Successful(emotes, notifyClientsOnAccount: false); return RequestResult.Successful(emotes, notifyClientsOnAccount: false);
} }
} }

View File

@@ -1,4 +1,5 @@
using HermesSocketLibrary.db; using HermesSocketLibrary.db;
using HermesSocketServer.Models;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -16,16 +17,16 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var temp = new Dictionary<string, object>() { { "user", sender } }; var temp = new Dictionary<string, object>() { { "user", channel.Id } };
var voices = new List<string>(); var voices = new List<string>();
string sql = $"SELECT v.name FROM \"TtsVoiceState\" s " string sql = $"SELECT v.name FROM \"TtsVoiceState\" s "
+ "INNER JOIN \"TtsVoice\" v ON s.\"ttsVoiceId\" = v.id " + "INNER JOIN \"TtsVoice\" v ON s.\"ttsVoiceId\" = v.id "
+ "WHERE \"userId\" = @user AND state = true"; + "WHERE \"userId\" = @user AND state = true";
await _database.Execute(sql, temp, (r) => voices.Add(r.GetString(0))); await _database.Execute(sql, temp, (r) => voices.Add(r.GetString(0)));
_logger.Information($"Fetched all enabled TTS voice for channel [channel: {sender}]"); _logger.Information($"Fetched all enabled TTS voice for channel [channel: {channel.Id}]");
return RequestResult.Successful(voices, notifyClientsOnAccount: false); return RequestResult.Successful(voices, notifyClientsOnAccount: false);
} }
} }

View File

@@ -1,5 +1,6 @@
using HermesSocketLibrary.db; using HermesSocketLibrary.db;
using HermesSocketLibrary.Requests.Messages; using HermesSocketLibrary.Requests.Messages;
using HermesSocketServer.Models;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -17,9 +18,9 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var temp = new Dictionary<string, object>() { { "user", sender } }; var temp = new Dictionary<string, object>() { { "user", channel.Id } };
var groups = new List<Group>(); var groups = new List<Group>();
string sql = $"SELECT id, name, priority FROM \"Group\" WHERE \"userId\" = @user"; string sql = $"SELECT id, name, priority FROM \"Group\" WHERE \"userId\" = @user";
@@ -47,7 +48,7 @@ namespace HermesSocketServer.Requests
Path = r.GetString(2), Path = r.GetString(2),
Allow = r.GetBoolean(3) Allow = r.GetBoolean(3)
})); }));
_logger.Information($"Fetched all redemptions for channel [channel: {sender}]"); _logger.Information($"Fetched all redemptions for channel [channel: {channel.Id}]");
var info = new GroupInfo() var info = new GroupInfo()
{ {

View File

@@ -1,4 +1,4 @@
using HermesSocketServer.Services; using HermesSocketServer.Models;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -7,21 +7,18 @@ namespace HermesSocketServer.Requests
{ {
public string Name => "get_policies"; public string Name => "get_policies";
public string[] RequiredKeys => []; public string[] RequiredKeys => [];
private ChannelManager _channels;
private ILogger _logger; private ILogger _logger;
public GetPolicies(ChannelManager channels, ILogger logger) public GetPolicies(ILogger logger)
{ {
_channels = channels;
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var channel = _channels.Get(sender);
var results = channel.Policies.Get().Values; var results = channel.Policies.Get().Values;
_logger.Information($"Fetched policies for channel [policy size: {results.Count}][channel: {sender}]"); _logger.Information($"Fetched policies for channel [policy size: {results.Count}][channel: {channel.Id}]");
return RequestResult.Successful(results, notifyClientsOnAccount: false); return RequestResult.Successful(results, notifyClientsOnAccount: false);
} }
} }

View File

@@ -1,6 +1,7 @@
using System.Text.Json; using System.Text.Json;
using HermesSocketLibrary.db; using HermesSocketLibrary.db;
using HermesSocketLibrary.Requests.Messages; using HermesSocketLibrary.Requests.Messages;
using HermesSocketServer.Models;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -20,9 +21,9 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var temp = new Dictionary<string, object>() { { "user", sender } }; var temp = new Dictionary<string, object>() { { "user", channel.Id } };
var redemptions = new List<RedeemableAction>(); var redemptions = new List<RedeemableAction>();
string sql = $"SELECT name, type, data FROM \"Action\" WHERE \"userId\" = @user"; string sql = $"SELECT name, type, data FROM \"Action\" WHERE \"userId\" = @user";
@@ -32,7 +33,7 @@ namespace HermesSocketServer.Requests
Type = r.GetString(1), Type = r.GetString(1),
Data = JsonSerializer.Deserialize<IDictionary<string, string>>(r.GetString(2), _options)! Data = JsonSerializer.Deserialize<IDictionary<string, string>>(r.GetString(2), _options)!
})); }));
_logger.Information($"Fetched all chatters' selected tts voice for channel [channel: {sender}]"); _logger.Information($"Fetched all chatters' selected tts voice for channel [channel: {channel.Id}]");
return RequestResult.Successful(redemptions, notifyClientsOnAccount: false); return RequestResult.Successful(redemptions, notifyClientsOnAccount: false);
} }
} }

View File

@@ -1,5 +1,6 @@
using HermesSocketLibrary.db; using HermesSocketLibrary.db;
using HermesSocketLibrary.Requests.Messages; using HermesSocketLibrary.Requests.Messages;
using HermesSocketServer.Models;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -17,9 +18,9 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var temp = new Dictionary<string, object>() { { "user", sender } }; var temp = new Dictionary<string, object>() { { "user", channel.Id } };
var redemptions = new List<Redemption>(); var redemptions = new List<Redemption>();
string sql = $"SELECT id, \"redemptionId\", \"actionName\", \"order\", state FROM \"Redemption\" WHERE \"userId\" = @user"; string sql = $"SELECT id, \"redemptionId\", \"actionName\", \"order\", state FROM \"Redemption\" WHERE \"userId\" = @user";
@@ -31,7 +32,7 @@ namespace HermesSocketServer.Requests
Order = r.GetInt32(3), Order = r.GetInt32(3),
State = r.GetBoolean(4) State = r.GetBoolean(4)
})); }));
_logger.Information($"Fetched all redemptions for channel [channel: {sender}]"); _logger.Information($"Fetched all redemptions for channel [channel: {channel.Id}]");
return RequestResult.Successful(redemptions, notifyClientsOnAccount: false); return RequestResult.Successful(redemptions, notifyClientsOnAccount: false);
} }
} }

View File

@@ -1,4 +1,4 @@
using HermesSocketServer.Services; using HermesSocketServer.Models;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -7,20 +7,17 @@ namespace HermesSocketServer.Requests
{ {
public string Name => "get_tts_users"; public string Name => "get_tts_users";
public string[] RequiredKeys => []; public string[] RequiredKeys => [];
private ChannelManager _channels;
private ILogger _logger; private ILogger _logger;
public GetTTSUsers(ChannelManager channels, ILogger logger) public GetTTSUsers(ILogger logger)
{ {
_channels = channels;
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var channel = _channels.Get(sender);
var results = channel.Chatters.Get().ToDictionary(p => p.Key, p => p.Value.VoiceId); var results = channel.Chatters.Get().ToDictionary(p => p.Key, p => p.Value.VoiceId);
_logger.Information($"Fetched all chatters' selected tts voice for channel [channel: {sender}]"); _logger.Information($"Fetched all chatters' selected tts voice for channel [channel: {channel.Id}]");
return RequestResult.Successful(results, notifyClientsOnAccount: false); return RequestResult.Successful(results, notifyClientsOnAccount: false);
} }
} }

View File

@@ -1,4 +1,5 @@
using HermesSocketLibrary.Requests.Messages; using HermesSocketLibrary.Requests.Messages;
using HermesSocketServer.Models;
using HermesSocketServer.Store; using HermesSocketServer.Store;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
@@ -17,7 +18,7 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
IEnumerable<VoiceDetails> voices = _voices.Get().Select(v => new VoiceDetails() IEnumerable<VoiceDetails> voices = _voices.Get().Select(v => new VoiceDetails()
{ {
@@ -25,7 +26,7 @@ namespace HermesSocketServer.Requests
Name = v.Value.Name Name = v.Value.Name
}); });
_logger.Information($"Fetched all TTS voices for channel [channel: {sender}]"); _logger.Information($"Fetched all TTS voices for channel [channel: {channel.Id}]");
return RequestResult.Successful(voices, notifyClientsOnAccount: false); return RequestResult.Successful(voices, notifyClientsOnAccount: false);
} }
} }

View File

@@ -1,5 +1,6 @@
using HermesSocketLibrary.db;
using HermesSocketLibrary.Requests.Messages; using HermesSocketLibrary.Requests.Messages;
using HermesSocketServer.Models;
using HermesSocketServer.Services;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -8,28 +9,20 @@ namespace HermesSocketServer.Requests
{ {
public string Name => "get_tts_word_filters"; public string Name => "get_tts_word_filters";
public string[] RequiredKeys => []; public string[] RequiredKeys => [];
private readonly Database _database; private ChannelManager _channels;
private readonly ILogger _logger; private ILogger _logger;
public GetTTSWordFilters(Database database, ILogger logger) public GetTTSWordFilters(ChannelManager channels, ILogger logger)
{ {
_database = database; _channels = channels;
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var temp = new Dictionary<string, object>() { { "user", sender } }; IEnumerable<TTSWordFilter> filters = channel.Filters.Get().Values;
IList<TTSWordFilter> filters = new List<TTSWordFilter>(); _logger.Information($"Fetched all word filters for channel [channel: {channel.Id}]");
string sql = $"SELECT id, search, replace FROM \"TtsWordFilter\" WHERE \"userId\" = @user";
await _database.Execute(sql, temp, (r) => filters.Add(new TTSWordFilter()
{
Id = r.GetString(0),
Search = r.GetString(1),
Replace = r.GetString(2)
}));
_logger.Information($"Fetched all word filters for channel [channel: {sender}]");
return RequestResult.Successful(filters, notifyClientsOnAccount: false); return RequestResult.Successful(filters, notifyClientsOnAccount: false);
} }
} }

View File

@@ -1,3 +1,5 @@
using HermesSocketServer.Models;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
{ {
public interface IRequest public interface IRequest
@@ -5,6 +7,6 @@ namespace HermesSocketServer.Requests
string Name { get; } string Name { get; }
string[] RequiredKeys { get; } string[] RequiredKeys { get; }
Task<RequestResult> Grant(string sender, IDictionary<string, object>? data); Task<RequestResult> Grant(Channel channel, IDictionary<string, object>? data);
} }
} }

View File

@@ -58,7 +58,7 @@ namespace HermesSocketServer.Requests
try try
{ {
return await request.Grant(sender, message.Data); return await request.Grant(channel, message.Data);
} }
catch (Exception e) catch (Exception e)
{ {

View File

@@ -1,3 +1,4 @@
using HermesSocketServer.Models;
using HermesSocketServer.Store; using HermesSocketServer.Store;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
@@ -16,16 +17,16 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
data["user"] = data["user"].ToString(); string user = data["user"].ToString()!;
data["voice"] = data["voice"].ToString(); string voice = data["voice"].ToString()!;
var success = _users.Modify(data["user"].ToString(), (user) => user.DefaultVoice = data["voice"].ToString()!); var success = _users.Modify(user, (user) => user.DefaultVoice = voice);
if (!success) if (!success)
return RequestResult.Failed("Unable to find user data.", notifyClientsOnAccount: false); return RequestResult.Failed("Unable to find user data.");
_logger.Information($"Updated default TTS voice for channel [channel: {sender}][voice: {data["voice"]}]"); _logger.Information($"Updated default TTS voice for channel [channel: {channel.Id}][voice: {voice}]");
return RequestResult.Successful(null); return RequestResult.Successful(null);
} }
} }

View File

@@ -17,7 +17,7 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
var id = Guid.Parse(data["id"].ToString()!); var id = Guid.Parse(data["id"].ToString()!);
string groupId = data["groupId"].ToString()!; string groupId = data["groupId"].ToString()!;
@@ -25,11 +25,10 @@ namespace HermesSocketServer.Requests
int count = int.Parse(data["count"].ToString()!); int count = int.Parse(data["count"].ToString()!);
int span = int.Parse(data["span"].ToString()!); int span = int.Parse(data["span"].ToString()!);
var channel = _channels.Get(sender)!;
bool result = channel.Policies.Set(id.ToString(), new PolicyMessage() bool result = channel.Policies.Set(id.ToString(), new PolicyMessage()
{ {
Id = id, Id = id,
UserId = sender, UserId = channel.Id,
GroupId = Guid.Parse(groupId), GroupId = Guid.Parse(groupId),
Path = path, Path = path,
Usage = count, Usage = count,
@@ -39,7 +38,7 @@ namespace HermesSocketServer.Requests
if (result) if (result)
{ {
var policy = channel.Policies.Get(id.ToString()); var policy = channel.Policies.Get(id.ToString());
_logger.Information($"Updated policy to channel [policy id: {id}][group id: {groupId}][path: {path}][count: {count}][span: {span}][channel: {sender}]"); _logger.Information($"Updated policy to channel [policy id: {id}][group id: {groupId}][path: {path}][count: {count}][span: {span}][channel: {channel.Id}]");
return RequestResult.Successful(policy); return RequestResult.Successful(policy);
} }
return RequestResult.Failed("Something went wrong when updating the cache."); return RequestResult.Failed("Something went wrong when updating the cache.");

View File

@@ -0,0 +1,45 @@
using HermesSocketLibrary.Requests.Messages;
using HermesSocketServer.Models;
using HermesSocketServer.Services;
using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests
{
public class UpdateTTSFilter : IRequest
{
public string Name => "update_tts_filter";
public string[] RequiredKeys => ["id", "search", "replace"];
private ChannelManager _channels;
private ILogger _logger;
public UpdateTTSFilter(ChannelManager channels, ILogger logger)
{
_channels = channels;
_logger = logger;
}
public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{
var id = data["id"].ToString()!;
string search = data["search"].ToString()!;
string replace = data["replace"].ToString()!;
var filter = new TTSWordFilter()
{
Id = id,
UserId = channel.Id,
Search = search,
Replace = replace,
};
bool result = channel.Filters.Set(id, filter);
if (result)
{
_logger.Information($"Updated filter to channel [filter id: {id}][search: {search}][replace: {replace}][channel: {channel.Id}]");
return RequestResult.Successful(filter);
}
return RequestResult.Failed("Something went wrong when updating the cache.");
}
}
}

View File

@@ -14,36 +14,34 @@ namespace HermesSocketServer.Requests
private readonly ServerConfiguration _configuration; private readonly ServerConfiguration _configuration;
private ILogger _logger; private ILogger _logger;
public UpdateTTSUser(ChannelManager channels, Database database, ServerConfiguration configuration, ILogger logger) public UpdateTTSUser(Database database, ServerConfiguration configuration, ILogger logger)
{ {
_database = database; _database = database;
_channels = channels;
_configuration = configuration; _configuration = configuration;
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
if (long.TryParse(data["chatter"].ToString(), out long chatterId)) if (long.TryParse(data["chatter"].ToString(), out long chatterId))
data["chatter"] = chatterId; data["chatter"] = chatterId;
data["voice"] = data["voice"].ToString(); data["voice"] = data["voice"].ToString()!;
data["user"] = sender; data["user"] = channel.Id;
var check = await _database.ExecuteScalar("SELECT state FROM \"TtsVoiceState\" WHERE \"userId\" = @user AND \"ttsVoiceId\" = @voice", data) ?? false; 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) if ((check is not bool state || !state) && chatterId != _configuration.Tts.OwnerId)
return RequestResult.Failed("Voice is either non-existent or disabled on this channel."); return RequestResult.Failed("Voice is either non-existent or disabled on this channel.");
var channel = _channels.Get(sender);
var result = channel.Chatters.Set(chatterId.ToString(), new ChatterVoice() var result = channel.Chatters.Set(chatterId.ToString(), new ChatterVoice()
{ {
UserId = sender, UserId = channel.Id,
ChatterId = chatterId, ChatterId = chatterId,
VoiceId = data["voice"].ToString()! VoiceId = data["voice"].ToString()!
}); });
if (result) if (result)
{ {
_logger.Information($"Updated chatter's [chatter: {data["chatter"]}] selected tts voice [voice: {data["voice"]}] in channel [channel: {sender}]"); _logger.Information($"Updated chatter's [chatter: {data["chatter"]}] selected tts voice [voice: {data["voice"]}] in channel [channel: {channel.Id}]");
return RequestResult.Successful(null); return RequestResult.Successful(null);
} }
return RequestResult.Failed("Soemthing went wrong when updating the cache."); return RequestResult.Failed("Soemthing went wrong when updating the cache.");

View File

@@ -17,19 +17,19 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
data["voice"] = data["voice"].ToString(); string voiceName = data["voice"].ToString()!;
data["voiceid"] = data["voiceid"].ToString(); string voiceId = data["voiceid"].ToString()!;
var result = _voices.Set(data["voiceid"].ToString(), new Voice() var result = _voices.Set(voiceId, new Voice()
{ {
Id = data["voiceid"].ToString()!, Id = voiceId,
Name = data["voice"].ToString()! Name = voiceName
}); });
if (result) if (result)
{ {
_logger.Information($"Updated voice's [voice id: {data["voiceid"]}] name [new name: {data["voice"]}]"); _logger.Information($"Updated voice's [voice id: {voiceId}] name [new name: {voiceName}]");
return RequestResult.Successful(null); return RequestResult.Successful(null);
} }
return RequestResult.Failed("Something went wrong when updating the cache."); return RequestResult.Failed("Something went wrong when updating the cache.");

View File

@@ -1,4 +1,5 @@
using HermesSocketLibrary.db; using HermesSocketLibrary.db;
using HermesSocketServer.Models;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
namespace HermesSocketServer.Requests namespace HermesSocketServer.Requests
@@ -16,11 +17,11 @@ namespace HermesSocketServer.Requests
_logger = logger; _logger = logger;
} }
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data) public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
{ {
data["voice"] = data["voice"].ToString(); data["voice"] = data["voice"].ToString();
data["state"] = data["state"].ToString() == "True"; data["state"] = data["state"].ToString() == "True";
data["user"] = sender; data["user"] = channel.Id;
string sql = "INSERT INTO \"TtsVoiceState\" (\"userId\", \"ttsVoiceId\", state) VALUES (@user, @voice, @state) ON CONFLICT (\"userId\", \"ttsVoiceId\") DO UPDATE SET state = @state"; string sql = "INSERT INTO \"TtsVoiceState\" (\"userId\", \"ttsVoiceId\", state) VALUES (@user, @voice, @state) ON CONFLICT (\"userId\", \"ttsVoiceId\") DO UPDATE SET state = @state";
var result = await _database.Execute(sql, data); var result = await _database.Execute(sql, data);

View File

@@ -78,20 +78,22 @@ namespace HermesSocketLibrary
await socket.Send(5, new LoggingMessage("Received no data in the message.", HermesLoggingLevel.Warn)); await socket.Send(5, new LoggingMessage("Received no data in the message.", HermesLoggingLevel.Warn));
continue; continue;
} }
else if (obj.OpCode == 0)
obj.Data = JsonSerializer.Deserialize<HeartbeatMessage>(obj.Data.ToString(), _options); string data = obj.Data.ToString()!;
if (obj.OpCode == 0)
obj.Data = JsonSerializer.Deserialize<HeartbeatMessage>(data, _options);
else if (obj.OpCode == 1) else if (obj.OpCode == 1)
obj.Data = JsonSerializer.Deserialize<HermesLoginMessage>(obj.Data.ToString(), _options); obj.Data = JsonSerializer.Deserialize<HermesLoginMessage>(data, _options);
else if (obj.OpCode == 3) else if (obj.OpCode == 3)
obj.Data = JsonSerializer.Deserialize<RequestMessage>(obj.Data.ToString(), _options); obj.Data = JsonSerializer.Deserialize<RequestMessage>(data, _options);
else if (obj.OpCode == 5) else if (obj.OpCode == 5)
obj.Data = JsonSerializer.Deserialize<LoggingMessage>(obj.Data.ToString(), _options); obj.Data = JsonSerializer.Deserialize<LoggingMessage>(data, _options);
else if (obj.OpCode == 6) else if (obj.OpCode == 6)
obj.Data = JsonSerializer.Deserialize<ChatterMessage>(obj.Data.ToString(), _options); obj.Data = JsonSerializer.Deserialize<ChatterMessage>(data, _options);
else if (obj.OpCode == 7) else if (obj.OpCode == 7)
obj.Data = JsonSerializer.Deserialize<EmoteDetailsMessage>(obj.Data.ToString(), _options); obj.Data = JsonSerializer.Deserialize<EmoteDetailsMessage>(data, _options);
else if (obj.OpCode == 8) else if (obj.OpCode == 8)
obj.Data = JsonSerializer.Deserialize<EmoteUsageMessage>(obj.Data.ToString(), _options); obj.Data = JsonSerializer.Deserialize<EmoteUsageMessage>(data, _options);
else else
{ {
await socket.Send(5, new LoggingMessage("Received an invalid message: " + message, HermesLoggingLevel.Error)); await socket.Send(5, new LoggingMessage("Received an invalid message: " + message, HermesLoggingLevel.Error));

View File

@@ -36,13 +36,14 @@ namespace HermesSocketServer.Services
{ {
return null; return null;
} }
}
var chatters = new ChatterStore(userId, _database, _logger); var chatters = new ChatterStore(userId, _database, _logger);
var policies = new PolicyStore(userId, _database, _logger); var policies = new PolicyStore(userId, _database, _logger);
await Task.WhenAll([ var filters = new TTSFilterStore(userId, _database, _logger);
Task.WaitAll([
chatters.Load(), chatters.Load(),
policies.Load(), policies.Load(),
filters.Load(),
]); ]);
var channel = new Channel() var channel = new Channel()
@@ -50,15 +51,14 @@ namespace HermesSocketServer.Services
Id = userId, Id = userId,
User = user, User = user,
Chatters = chatters, Chatters = chatters,
Policies = policies Policies = policies,
Filters = filters,
}; };
lock (_lock)
{
_channels.Add(userId, channel); _channels.Add(userId, channel);
}
return channel; return channel;
} }
}
public Channel? Get(string channelId) public Channel? Get(string channelId)
{ {
@@ -75,6 +75,7 @@ namespace HermesSocketServer.Services
await Task.WhenAll([ await Task.WhenAll([
channel.Chatters.Save(), channel.Chatters.Save(),
channel.Policies.Save(), channel.Policies.Save(),
channel.Filters.Save(),
]); ]);
} }
@@ -86,6 +87,7 @@ namespace HermesSocketServer.Services
await Task.WhenAll([ await Task.WhenAll([
channel.Chatters.Save(), channel.Chatters.Save(),
channel.Policies.Save(), channel.Policies.Save(),
channel.Filters.Save(),
]); ]);
} }
} }

View File

@@ -13,6 +13,7 @@ namespace HermesSocketServer.Socket.Handlers
private readonly HashSet<string> _history; private readonly HashSet<string> _history;
private readonly EmoteUsageMessage[] _array; private readonly EmoteUsageMessage[] _array;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly object _lock;
private int _index; private int _index;
@@ -22,6 +23,7 @@ namespace HermesSocketServer.Socket.Handlers
_logger = logger; _logger = logger;
_history = new HashSet<string>(101); _history = new HashSet<string>(101);
_array = new EmoteUsageMessage[100]; _array = new EmoteUsageMessage[100];
_lock = new object();
_index = -1; _index = -1;
} }
@@ -31,7 +33,7 @@ namespace HermesSocketServer.Socket.Handlers
if (message is not EmoteUsageMessage data || sender.Id == null) if (message is not EmoteUsageMessage data || sender.Id == null)
return; return;
lock (_logger) lock (_lock)
{ {
if (_history.Contains(data.MessageId)) if (_history.Contains(data.MessageId))
{ {

View File

@@ -77,6 +77,7 @@ namespace HermesSocketServer.Socket.Handlers
var ack = new LoginAckMessage() var ack = new LoginAckMessage()
{ {
UserId = userId, UserId = userId,
SessionId = sender.UID,
OwnerId = _configuration.Tts.OwnerId, OwnerId = _configuration.Tts.OwnerId,
Admin = sender.Admin, Admin = sender.Admin,
WebLogin = data.WebLogin, WebLogin = data.WebLogin,

View File

@@ -35,17 +35,18 @@ namespace HermesSocketServer.Socket.Handlers
_logger.Error(e, $"Failed to grant a request of type '{data.Type}'."); _logger.Error(e, $"Failed to grant a request of type '{data.Type}'.");
} }
if (result == null || !result.Success) if (result == null)
return; return;
var ack = new RequestAckMessage() var ack = new RequestAckMessage()
{ {
Request = data, Request = data,
Data = result.Result, Data = result.Success ? result.Result : null,
Nounce = data.Nounce Nounce = data.Nounce,
Error = result.Success ? null : result.Result?.ToString()
}; };
if (!result.NotifyClientsOnAccount) if (!result.NotifyClientsOnAccount || !result.Success)
{ {
await sender.Send(4, ack); await sender.Send(4, ack);
return; return;

View File

@@ -2,7 +2,6 @@ using System.Net;
using System.Text.Json; using System.Text.Json;
using HermesSocketLibrary; using HermesSocketLibrary;
using HermesSocketLibrary.db; using HermesSocketLibrary.db;
using HermesSocketLibrary.Requests;
using HermesSocketServer; using HermesSocketServer;
using HermesSocketServer.Requests; using HermesSocketServer.Requests;
using HermesSocketServer.Socket; using HermesSocketServer.Socket;
@@ -85,9 +84,11 @@ s.AddSingleton<UserStore>();
// Request handlers // Request handlers
s.AddSingleton<IRequest, CreatePolicy>(); s.AddSingleton<IRequest, CreatePolicy>();
s.AddSingleton<IRequest, CreateTTSFilter>();
s.AddSingleton<IRequest, CreateTTSUser>(); s.AddSingleton<IRequest, CreateTTSUser>();
s.AddSingleton<IRequest, CreateTTSVoice>(); s.AddSingleton<IRequest, CreateTTSVoice>();
s.AddSingleton<IRequest, DeletePolicy>(); s.AddSingleton<IRequest, DeletePolicy>();
s.AddSingleton<IRequest, DeleteTTSFilter>();
s.AddSingleton<IRequest, DeleteTTSVoice>(); s.AddSingleton<IRequest, DeleteTTSVoice>();
s.AddSingleton<IRequest, GetChatterIds>(); s.AddSingleton<IRequest, GetChatterIds>();
s.AddSingleton<IRequest, GetConnections>(); s.AddSingleton<IRequest, GetConnections>();
@@ -101,6 +102,7 @@ s.AddSingleton<IRequest, GetPolicies>();
s.AddSingleton<IRequest, GetTTSUsers>(); s.AddSingleton<IRequest, GetTTSUsers>();
s.AddSingleton<IRequest, GetTTSVoices>(); s.AddSingleton<IRequest, GetTTSVoices>();
s.AddSingleton<IRequest, GetTTSWordFilters>(); s.AddSingleton<IRequest, GetTTSWordFilters>();
s.AddSingleton<IRequest, UpdateTTSFilter>();
s.AddSingleton<IRequest, UpdateTTSUser>(); s.AddSingleton<IRequest, UpdateTTSUser>();
s.AddSingleton<IRequest, UpdateTTSVoice>(); s.AddSingleton<IRequest, UpdateTTSVoice>();
s.AddSingleton<IRequest, UpdateDefaultTTSVoice>(); s.AddSingleton<IRequest, UpdateDefaultTTSVoice>();

View File

@@ -72,9 +72,9 @@ namespace HermesSocketServer.Store
count = list.Count; count = list.Count;
sql = _generator.GeneratePreparedInsertSql("TtsChatVoice", count, ["userId", "chatterId", "ttsVoiceId"]); sql = _generator.GeneratePreparedInsertSql("TtsChatVoice", count, ["userId", "chatterId", "ttsVoiceId"]);
_logger.Debug($"User - Adding {count} rows to database: {sql}"); _logger.Debug($"Chatter - Adding {count} rows to database: {sql}");
var values = list.Select(id => _store[id]).Where(v => v != null); var values = list.Select(id => _store[id]).Where(v => v != null);
await _generator.DoPreparedStatement(_database, sql, values, ["id", "name", "email", "role", "ttsDefaultVoice"]); await _generator.DoPreparedStatement(_database, sql, values, ["userId", "chatterId", "ttsVoiceId"]);
} }
if (_modified.Any()) if (_modified.Any())
{ {
@@ -86,9 +86,9 @@ namespace HermesSocketServer.Store
count = list.Count; count = list.Count;
sql = _generator.GeneratePreparedUpdateSql("TtsChatVoice", count, ["userId", "chatterId"], ["ttsVoiceId"]); sql = _generator.GeneratePreparedUpdateSql("TtsChatVoice", count, ["userId", "chatterId"], ["ttsVoiceId"]);
_logger.Debug($"User - Modifying {count} rows in database: {sql}"); _logger.Debug($"Chatter - Modifying {count} rows in database: {sql}");
var values = list.Select(id => _store[id]).Where(v => v != null); var values = list.Select(id => _store[id]).Where(v => v != null);
await _generator.DoPreparedStatement(_database, sql, values, ["id", "name", "email", "role", "ttsDefaultVoice"]); await _generator.DoPreparedStatement(_database, sql, values, ["userId", "chatterId", "ttsVoiceId"]);
} }
if (_deleted.Any()) if (_deleted.Any())
{ {
@@ -100,8 +100,8 @@ namespace HermesSocketServer.Store
count = list.Count; count = list.Count;
sql = _generator.GeneratePreparedDeleteSql("TtsChatVoice", count, ["userId", "chatterId"]); sql = _generator.GeneratePreparedDeleteSql("TtsChatVoice", count, ["userId", "chatterId"]);
_logger.Debug($"User - Deleting {count} rows from database: {sql}"); _logger.Debug($"Chatter - Deleting {count} rows from database: {sql}");
await _generator.DoPreparedStatementRaw(_database, sql, list, ["id"]); await _generator.DoPreparedStatementRaw(_database, sql, list, ["userId", "chatterId"]);
} }
} }
} }

109
Store/TTSFilterStore.cs Normal file
View File

@@ -0,0 +1,109 @@
using System.Collections.Immutable;
using HermesSocketLibrary.db;
using HermesSocketLibrary.Requests.Messages;
namespace HermesSocketServer.Store
{
public class TTSFilterStore : GroupSaveStore<string, TTSWordFilter>
{
private readonly string _userId;
private readonly Database _database;
private readonly Serilog.ILogger _logger;
private readonly GroupSaveSqlGenerator<TTSWordFilter> _generator;
public TTSFilterStore(string userId, Database database, Serilog.ILogger logger) : base(logger)
{
_userId = userId;
_database = database;
_logger = logger;
var ctp = new Dictionary<string, string>
{
{ "id", "Id" },
{ "userId", "UserId" },
{ "search", "Search" },
{ "replace", "Replace" },
};
_generator = new GroupSaveSqlGenerator<TTSWordFilter>(ctp, _logger);
}
public override async Task Load()
{
var data = new Dictionary<string, object>() { { "user", _userId } };
string sql = $"SELECT id, search, replace FROM \"TtsWordFilter\" WHERE \"userId\" = @user";
await _database.Execute(sql, data, (reader) =>
{
var id = reader.GetString(0);
_store.Add(id.ToString(), new TTSWordFilter()
{
Id = id,
Search = reader.GetString(1),
Replace = reader.GetString(2)
});
});
_logger.Information($"Loaded {_store.Count} TTS chatter voices from database.");
}
protected override void OnInitialAdd(string key, TTSWordFilter value)
{
}
protected override void OnInitialModify(string key, TTSWordFilter value)
{
}
protected override void OnInitialRemove(string key)
{
}
public override async Task Save()
{
int count = 0;
string sql = string.Empty;
ImmutableList<string>? list = null;
if (_added.Any())
{
lock (_lock)
{
list = _added.ToImmutableList();
_added.Clear();
}
count = list.Count;
sql = _generator.GeneratePreparedInsertSql("TtsWordFilter", count, ["id", "userId", "search", "replace"]);
_logger.Debug($"TTS Filter - Adding {count} rows to database: {sql}");
var values = list.Select(id => _store[id]).Where(v => v != null);
await _generator.DoPreparedStatement(_database, sql, values, ["id", "userId", "search", "replace"]);
}
if (_modified.Any())
{
lock (_lock)
{
list = _modified.ToImmutableList();
_modified.Clear();
}
count = list.Count;
sql = _generator.GeneratePreparedUpdateSql("TtsWordFilter", count, ["id"], ["userId", "search", "replace"]);
_logger.Debug($"TTS Filter - Modifying {count} rows in database: {sql}");
var values = list.Select(id => _store[id]).Where(v => v != null);
await _generator.DoPreparedStatement(_database, sql, values, ["id", "userId", "search", "replace"]);
}
if (_deleted.Any())
{
lock (_lock)
{
list = _deleted.ToImmutableList();
_deleted.Clear();
}
count = list.Count;
sql = _generator.GeneratePreparedDeleteSql("TtsWordFilter", count, ["id"]);
_logger.Debug($"TTS Filter - Deleting {count} rows from database: {sql}");
await _generator.DoPreparedStatementRaw(_database, sql, list, ["id"]);
}
}
}
}

View File

@@ -75,7 +75,7 @@ namespace HermesSocketServer.Store
count = list.Count; count = list.Count;
sql = _generator.GeneratePreparedInsertSql("TtsVoice", count, ["id", "name"]); sql = _generator.GeneratePreparedInsertSql("TtsVoice", count, ["id", "name"]);
_logger.Debug($"User - Adding {count} rows to database: {sql}"); _logger.Debug($"Voice - Adding {count} rows to database: {sql}");
var values = list.Select(id => _store[id]).Where(v => v != null); var values = list.Select(id => _store[id]).Where(v => v != null);
await _generator.DoPreparedStatement(_database, sql, values, ["id", "name", "email", "role", "ttsDefaultVoice"]); await _generator.DoPreparedStatement(_database, sql, values, ["id", "name", "email", "role", "ttsDefaultVoice"]);
} }
@@ -89,7 +89,7 @@ namespace HermesSocketServer.Store
count = list.Count; count = list.Count;
sql = _generator.GeneratePreparedUpdateSql("TtsVoice", count, ["id"], ["name"]); sql = _generator.GeneratePreparedUpdateSql("TtsVoice", count, ["id"], ["name"]);
_logger.Debug($"User - Modifying {count} rows in database: {sql}"); _logger.Debug($"Voice - Modifying {count} rows in database: {sql}");
var values = list.Select(id => _store[id]).Where(v => v != null); var values = list.Select(id => _store[id]).Where(v => v != null);
await _generator.DoPreparedStatement(_database, sql, values, ["id", "name", "email", "role", "ttsDefaultVoice"]); await _generator.DoPreparedStatement(_database, sql, values, ["id", "name", "email", "role", "ttsDefaultVoice"]);
} }
@@ -103,7 +103,7 @@ namespace HermesSocketServer.Store
count = list.Count; count = list.Count;
sql = _generator.GeneratePreparedDeleteSql("TtsVoice", count, ["id"]); sql = _generator.GeneratePreparedDeleteSql("TtsVoice", count, ["id"]);
_logger.Debug($"User - Deleting {count} rows from database: {sql}"); _logger.Debug($"Voice - Deleting {count} rows from database: {sql}");
await _generator.DoPreparedStatementRaw(_database, sql, list, ["id"]); await _generator.DoPreparedStatementRaw(_database, sql, list, ["id"]);
} }
} }