Compare commits
29 Commits
e3c78d96fa
...
master
Author | SHA1 | Date | |
---|---|---|---|
c7904f120d | |||
c80f1f2aa0 | |||
07cb396dd7 | |||
de3455ee8a | |||
6cd8997301 | |||
4d0743c4aa | |||
fd0bca5c7c | |||
3e717522c2 | |||
6d955f245a | |||
422cd91db2 | |||
ee3f128a9f | |||
b00c72ec2a | |||
00cea32cfa | |||
125f71e779 | |||
a9542b08fb | |||
467c3cf0b0 | |||
3429c8f8dc | |||
538bf07454 | |||
525725a7e5 | |||
21cb5c9453 | |||
8277ea0154 | |||
06bfe110bb | |||
6176e6f3b9 | |||
4979553c74 | |||
5618b28c49 | |||
61151bef0c | |||
aac73563d0 | |||
e7b06f1634 | |||
94e0d54c31 |
@ -4,9 +4,16 @@ namespace HermesSocketServer.Models
|
|||||||
{
|
{
|
||||||
public class Channel
|
public class Channel
|
||||||
{
|
{
|
||||||
public string Id { get; set; }
|
public required string Id { get; set; }
|
||||||
public User User { get; set; }
|
public required User User { get; set; }
|
||||||
public ChatterStore Chatters { get; set; }
|
public required ChatterStore Chatters { get; set; }
|
||||||
public PolicyStore Policies { get; set; }
|
public required ConnectionStore Connections { get; set; }
|
||||||
|
public required GroupStore Groups { get; set; }
|
||||||
|
public required GroupPermissionStore GroupPermissions { get; set; }
|
||||||
|
public required PolicyStore Policies { get; set; }
|
||||||
|
public required TTSFilterStore Filters { get; set; }
|
||||||
|
public required ActionStore Actions { get; set; }
|
||||||
|
public required RedemptionStore Redemptions { get; set; }
|
||||||
|
public required VoiceStateStore VoiceStates { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -2,8 +2,8 @@ namespace HermesSocketServer.Models
|
|||||||
{
|
{
|
||||||
public class ChatterVoice
|
public class ChatterVoice
|
||||||
{
|
{
|
||||||
public string ChatterId { get; set; }
|
public long ChatterId { get; set; }
|
||||||
public string UserId { get; set; }
|
public required string UserId { get; set; }
|
||||||
public string VoiceId { get; set; }
|
public required string VoiceId { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,12 +0,0 @@
|
|||||||
namespace HermesSocketServer.Store
|
|
||||||
{
|
|
||||||
public class Policy
|
|
||||||
{
|
|
||||||
public string Id { get; set; }
|
|
||||||
public string UserId { get; set; }
|
|
||||||
public string GroupId { get; set; }
|
|
||||||
public string Path { get; set; }
|
|
||||||
public int Usage { get; set; }
|
|
||||||
public TimeSpan Span { get; set; }
|
|
||||||
}
|
|
||||||
}
|
|
@ -2,10 +2,10 @@ namespace HermesSocketServer.Models
|
|||||||
{
|
{
|
||||||
public class User
|
public class User
|
||||||
{
|
{
|
||||||
public string Id { get; set; }
|
public required string Id { get; set; }
|
||||||
public string Name { get; set; }
|
public required string Name { get; set; }
|
||||||
public string Email { get; set; }
|
public required string Email { get; set; }
|
||||||
public string Role { get; set; }
|
public required string Role { get; set; }
|
||||||
public string DefaultVoice { get; set; }
|
public required string DefaultVoice { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,8 +0,0 @@
|
|||||||
namespace HermesSocketServer.Models
|
|
||||||
{
|
|
||||||
public class Voice
|
|
||||||
{
|
|
||||||
public string Id { get; set; }
|
|
||||||
public string Name { get; set; }
|
|
||||||
}
|
|
||||||
}
|
|
@ -51,12 +51,15 @@ namespace HermesSocketServer.Quests
|
|||||||
});
|
});
|
||||||
|
|
||||||
string sql2 = "SELECT id FROM \"Quest\" WHERE type = @type AND start = @start";
|
string sql2 = "SELECT id FROM \"Quest\" WHERE type = @type AND start = @start";
|
||||||
int? questId = (int?)await _database.ExecuteScalar(sql, c =>
|
int? questId = (int?)await _database.ExecuteScalar(sql2, c =>
|
||||||
{
|
{
|
||||||
c.Parameters.AddWithValue("@type", temp.Type);
|
c.Parameters.AddWithValue("@type", temp.Type);
|
||||||
c.Parameters.AddWithValue("@start", temp.StartTime);
|
c.Parameters.AddWithValue("@start", temp.StartTime);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (questId == null)
|
||||||
|
return;
|
||||||
|
|
||||||
var quest = new DailyQuest((short)questId.Value, task, date);
|
var quest = new DailyQuest((short)questId.Value, task, date);
|
||||||
_quests.Add(quest.Id, quest);
|
_quests.Add(quest.Id, quest);
|
||||||
}
|
}
|
||||||
@ -88,12 +91,15 @@ namespace HermesSocketServer.Quests
|
|||||||
});
|
});
|
||||||
|
|
||||||
string sql2 = "SELECT id FROM \"Quest\" WHERE type = @type AND start = @start";
|
string sql2 = "SELECT id FROM \"Quest\" WHERE type = @type AND start = @start";
|
||||||
int? questId = (int?)await _database.ExecuteScalar(sql, c =>
|
int? questId = (int?)await _database.ExecuteScalar(sql2, c =>
|
||||||
{
|
{
|
||||||
c.Parameters.AddWithValue("@type", temp.Type);
|
c.Parameters.AddWithValue("@type", temp.Type);
|
||||||
c.Parameters.AddWithValue("@start", temp.StartTime);
|
c.Parameters.AddWithValue("@start", temp.StartTime);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (questId == null)
|
||||||
|
return;
|
||||||
|
|
||||||
var quest = new WeeklyQuest((short)questId.Value, task, date);
|
var quest = new WeeklyQuest((short)questId.Value, task, date);
|
||||||
_quests.Add(quest.Id, quest);
|
_quests.Add(quest.Id, quest);
|
||||||
}
|
}
|
||||||
|
50
Requests/CreateConnection.cs
Normal file
50
Requests/CreateConnection.cs
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
using HermesSocketLibrary.Socket.Data;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class CreateConnection : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "create_connection";
|
||||||
|
public string[] RequiredKeys => ["name", "type", "client_id", "access_token", "grant_type", "scope", "expiration"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public CreateConnection(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
string name = data["name"].ToString()!;
|
||||||
|
string type = data["type"].ToString()!;
|
||||||
|
string clientId = data["client_id"].ToString()!;
|
||||||
|
string accessToken = data["access_token"].ToString()!;
|
||||||
|
string grantType = data["grant_type"].ToString()!;
|
||||||
|
string scope = data["scope"].ToString()!;
|
||||||
|
if (!DateTime.TryParse(data["expiration"].ToString()!, out var expiresAt))
|
||||||
|
return Task.FromResult(RequestResult.Failed("Expiration needs to be a date time string."));
|
||||||
|
|
||||||
|
var connection = new Connection()
|
||||||
|
{
|
||||||
|
UserId = channel.Id,
|
||||||
|
Name = name,
|
||||||
|
Type = type,
|
||||||
|
ClientId = clientId,
|
||||||
|
AccessToken = accessToken,
|
||||||
|
GrantType = grantType,
|
||||||
|
Scope = scope,
|
||||||
|
ExpiresAt = expiresAt,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool result = channel.Connections.Set(name, connection);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Added connection to channel [name: {name}][type: {type}][scope: {scope}][expiration: {expiresAt}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(connection));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
51
Requests/CreateGroup.cs
Normal file
51
Requests/CreateGroup.cs
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using HermesSocketServer.Store;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class CreateGroup : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "create_group";
|
||||||
|
public string[] RequiredKeys => ["name", "priority"];
|
||||||
|
private readonly DatabaseTable _table;
|
||||||
|
private readonly Database _database;
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public CreateGroup([FromKeyedServices("ChatterGroup")] DatabaseTable table, Database database, ILogger logger)
|
||||||
|
{
|
||||||
|
_table = table;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = Guid.NewGuid();
|
||||||
|
string name = data["name"].ToString()!;
|
||||||
|
if (!int.TryParse(data["priority"].ToString()!, out var priority))
|
||||||
|
return Task.FromResult(RequestResult.Failed("Priority needs to be an integer."));
|
||||||
|
|
||||||
|
var group = new Group()
|
||||||
|
{
|
||||||
|
Id = id.ToString(),
|
||||||
|
UserId = channel.Id,
|
||||||
|
Name = name,
|
||||||
|
Priority = priority,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool result = channel.Groups.Set(id.ToString(), group);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
var store = new ChatterGroupStore(channel.Id, group.Id, _table, _database, _logger);
|
||||||
|
channel.Groups.Chatters.Add(group.Id, store);
|
||||||
|
_logger.Information($"Added group to channel [group id: {id}][name: {name}][priority: {priority}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(group));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
46
Requests/CreateGroupChatter.cs
Normal file
46
Requests/CreateGroupChatter.cs
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class CreateGroupChatter : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "create_group_chatter";
|
||||||
|
public string[] RequiredKeys => ["group", "chatter", "label"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public CreateGroupChatter(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
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."));
|
||||||
|
string chatterLabel = data["label"].ToString()!;
|
||||||
|
|
||||||
|
if (!channel.Groups.Chatters.TryGetValue(groupId, out var chatters))
|
||||||
|
return Task.FromResult(RequestResult.Failed($"The group does not exist."));
|
||||||
|
|
||||||
|
var groupChatter = new GroupChatter()
|
||||||
|
{
|
||||||
|
UserId = channel.Id,
|
||||||
|
GroupId = groupId,
|
||||||
|
ChatterId = chatterId,
|
||||||
|
ChatterLabel = chatterLabel,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool result = chatters.Set(chatterId.ToString(), groupChatter);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Added group chatter to channel [group id: {id}][group id: {groupId}][chatter id: {chatterId}][chatter label: {chatterLabel}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(groupChatter));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
48
Requests/CreateGroupPermission.cs
Normal file
48
Requests/CreateGroupPermission.cs
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class CreateGroupPermission : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "create_group_permission";
|
||||||
|
public string[] RequiredKeys => ["group", "path", "allow"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public CreateGroupPermission(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = Guid.NewGuid();
|
||||||
|
Guid groupId = new Guid(data["group"].ToString()!);
|
||||||
|
string path = data["path"].ToString()!;
|
||||||
|
bool? allow = bool.TryParse(data["allow"].ToString()!, out bool a) ? a : null;
|
||||||
|
|
||||||
|
var permission = new GroupPermission()
|
||||||
|
{
|
||||||
|
Id = id.ToString(),
|
||||||
|
UserId = channel.Id,
|
||||||
|
GroupId = groupId,
|
||||||
|
Path = path,
|
||||||
|
Allow = allow,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (channel.GroupPermissions.Get().Values.Any(p => p.GroupId == groupId && p.Path == path))
|
||||||
|
{
|
||||||
|
return Task.FromResult(RequestResult.Failed("Permission exists already."));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool result = channel.GroupPermissions.Set(id.ToString(), permission);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Added group permission to channel [permission id: {id}][group id: {groupId}][path: {path}][allow: {allow}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(permission));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
45
Requests/CreatePolicy.cs
Normal file
45
Requests/CreatePolicy.cs
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
using HermesSocketServer.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class CreatePolicy : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "create_policy";
|
||||||
|
public string[] RequiredKeys => ["groupId", "path", "count", "span"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public CreatePolicy(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = Guid.NewGuid();
|
||||||
|
string groupId = data["groupId"].ToString()!;
|
||||||
|
string path = data["path"].ToString()!;
|
||||||
|
int count = int.Parse(data["count"].ToString()!);
|
||||||
|
int span = int.Parse(data["span"].ToString()!);
|
||||||
|
|
||||||
|
var policy = new Policy()
|
||||||
|
{
|
||||||
|
Id = id,
|
||||||
|
UserId = channel.Id,
|
||||||
|
GroupId = Guid.Parse(groupId),
|
||||||
|
Path = path,
|
||||||
|
Usage = count,
|
||||||
|
Span = span,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool result = channel.Policies.Set(id.ToString(), policy);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Added policy to channel [policy id: {id}][group id: {groupId}][path: {path}][count: {count}][span: {span}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(policy));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
55
Requests/CreateRedeemableAction.cs
Normal file
55
Requests/CreateRedeemableAction.cs
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class CreateRedeemableAction : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "create_redeemable_action";
|
||||||
|
public string[] RequiredKeys => ["name", "has_message", "type", "data"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public CreateRedeemableAction(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
string name = data["name"].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
|
||||||
|
{
|
||||||
|
dict = JsonSerializer.Deserialize<IDictionary<string, string>>(d)!;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_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."));
|
||||||
|
}
|
||||||
|
|
||||||
|
var action = new RedeemableAction()
|
||||||
|
{
|
||||||
|
UserId = channel.Id,
|
||||||
|
Name = name,
|
||||||
|
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}][has message: {hasMessage}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(action));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
47
Requests/CreateRedemption.cs
Normal file
47
Requests/CreateRedemption.cs
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class CreateRedemption : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "create_redemption";
|
||||||
|
public string[] RequiredKeys => ["redemption", "action", "order"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public CreateRedemption(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = Guid.NewGuid();
|
||||||
|
string redemptionId = data["redemption"].ToString()!;
|
||||||
|
string actionName = data["action"].ToString()!;
|
||||||
|
if (channel.Actions.Get(actionName) == null)
|
||||||
|
return Task.FromResult(RequestResult.Failed("Action Name must be an existing action."));
|
||||||
|
if (!int.TryParse(data["order"].ToString()!, out var order))
|
||||||
|
return Task.FromResult(RequestResult.Failed("Order must be an integer."));
|
||||||
|
|
||||||
|
var redemption = new Redemption()
|
||||||
|
{
|
||||||
|
Id = id.ToString(),
|
||||||
|
UserId = channel.Id,
|
||||||
|
RedemptionId = redemptionId,
|
||||||
|
ActionName = actionName,
|
||||||
|
Order = order,
|
||||||
|
State = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool result = channel.Redemptions.Set(id.ToString(), redemption);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Added redemption to channel [redemption id: {id}][twitch redemption id: {redemptionId}][action: {actionName}][order: {order}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(redemption));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
46
Requests/CreateTTSFilter.cs
Normal file
46
Requests/CreateTTSFilter.cs
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
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 Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = Guid.NewGuid();
|
||||||
|
string search = data["search"].ToString()!;
|
||||||
|
string replace = data["replace"].ToString()!;
|
||||||
|
int flag = 0;
|
||||||
|
if (data.TryGetValue("flag", out var flagObject)) {
|
||||||
|
int.TryParse(flagObject.ToString(), out flag);
|
||||||
|
}
|
||||||
|
|
||||||
|
var filter = new TTSWordFilter()
|
||||||
|
{
|
||||||
|
Id = id.ToString(),
|
||||||
|
UserId = channel.Id,
|
||||||
|
Search = search,
|
||||||
|
Replace = replace,
|
||||||
|
Flag = flag,
|
||||||
|
};
|
||||||
|
|
||||||
|
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 Task.FromResult(RequestResult.Successful(filter));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,4 @@
|
|||||||
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
|
||||||
@ -8,48 +6,41 @@ namespace HermesSocketServer.Requests
|
|||||||
public class CreateTTSUser : IRequest
|
public class CreateTTSUser : IRequest
|
||||||
{
|
{
|
||||||
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 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(ServerConfiguration configuration, ILogger logger)
|
||||||
{
|
{
|
||||||
_database = database;
|
|
||||||
_channels = channels;
|
|
||||||
_configuration = configuration;
|
_configuration = configuration;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public 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;
|
return Task.FromResult(RequestResult.Failed("Invalid Twitch user id."));
|
||||||
else
|
|
||||||
return RequestResult.Failed("Invalid Twitch user id");
|
|
||||||
|
|
||||||
data["voice"] = data["voice"].ToString();
|
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;
|
var check = channel.VoiceStates.Get(voiceId)?.Enabled ?? false;
|
||||||
if ((check is not bool state || !state) && chatterId != _configuration.Tts.OwnerId)
|
if (!check && chatterId != _configuration.Tts.OwnerId)
|
||||||
return RequestResult.Failed("Voice is disabled on this channel.");
|
return Task.FromResult(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.ToString(),
|
ChatterId = chatterId,
|
||||||
VoiceId = data["voice"].ToString()!
|
VoiceId = data["voice"].ToString()!
|
||||||
});
|
});
|
||||||
|
|
||||||
if (result)
|
if (result)
|
||||||
{
|
{
|
||||||
_logger.Information($"Selected a tts voice [voice: {data["voice"]}] for user [chatter: {data["chatter"]}] in channel [channel: {data["user"]}]");
|
_logger.Information($"Selected a tts voice [voice: {voiceId}] for user [chatter: {chatterId}] in channel [channel: {channel.Id}]");
|
||||||
return RequestResult.Successful(null);
|
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."));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,3 +1,4 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
using HermesSocketServer.Models;
|
using HermesSocketServer.Models;
|
||||||
using HermesSocketServer.Store;
|
using HermesSocketServer.Store;
|
||||||
using ILogger = Serilog.ILogger;
|
using ILogger = Serilog.ILogger;
|
||||||
@ -8,34 +9,33 @@ namespace HermesSocketServer.Requests
|
|||||||
{
|
{
|
||||||
public string Name => "create_tts_voice";
|
public string Name => "create_tts_voice";
|
||||||
public string[] RequiredKeys => ["voice"];
|
public string[] RequiredKeys => ["voice"];
|
||||||
private IStore<string, Voice> _voices;
|
private IStore<string, TTSVoice> _voices;
|
||||||
private ILogger _logger;
|
private ILogger _logger;
|
||||||
private Random _random;
|
private Random _random;
|
||||||
|
|
||||||
public CreateTTSVoice(VoiceStore voices, ILogger logger)
|
public CreateTTSVoice(IStore<string, TTSVoice> voices, ILogger logger)
|
||||||
{
|
{
|
||||||
_voices = voices;
|
_voices = voices;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_random = new Random();
|
_random = new Random();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public 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 TTSVoice()
|
||||||
{
|
{
|
||||||
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 Task.FromResult(RequestResult.Successful(id));
|
||||||
}
|
}
|
||||||
return RequestResult.Failed("Something went wrong when updating the cache.");
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
}
|
}
|
||||||
|
|
||||||
private string RandomString(int length)
|
private string RandomString(int length)
|
||||||
|
32
Requests/DeleteConnection.cs
Normal file
32
Requests/DeleteConnection.cs
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class DeleteConnection : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "delete_connection";
|
||||||
|
public string[] RequiredKeys => ["name"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public DeleteConnection(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var connectionName = data["name"].ToString()!;
|
||||||
|
|
||||||
|
var result = channel.Connections.Remove(connectionName);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Deleted a connection by name [connection name: {connectionName}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning($"Connection Name does not exist [connection name: {connectionName}]");
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
67
Requests/DeleteGroup.cs
Normal file
67
Requests/DeleteGroup.cs
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class DeleteGroup : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "delete_group";
|
||||||
|
public string[] RequiredKeys => ["id"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public DeleteGroup(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var groupId = data["id"].ToString()!;
|
||||||
|
|
||||||
|
var result = channel.Groups.Remove(groupId);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
var permissions = channel.GroupPermissions.Get().Values
|
||||||
|
.Where(p => p.GroupId.ToString() == groupId);
|
||||||
|
|
||||||
|
Task? chattersSave = null;
|
||||||
|
if (channel.Groups.Chatters.TryGetValue(groupId, out var chatters))
|
||||||
|
{
|
||||||
|
var filteredChatters = chatters.Get().Values.Where(c => c.GroupId == groupId).ToArray();
|
||||||
|
if (filteredChatters.Any())
|
||||||
|
{
|
||||||
|
foreach (var chatter in filteredChatters)
|
||||||
|
{
|
||||||
|
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}]");
|
||||||
|
}
|
||||||
|
|
||||||
|
chattersSave = chatters.Save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var permission in permissions)
|
||||||
|
{
|
||||||
|
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}]");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (chattersSave != null)
|
||||||
|
await Task.WhenAll(chattersSave, channel.GroupPermissions.Save());
|
||||||
|
else
|
||||||
|
await channel.GroupPermissions.Save();
|
||||||
|
|
||||||
|
if (!channel.Groups.Chatters.Remove(groupId))
|
||||||
|
_logger.Warning($"Failed to delete group chatters from inner store [group id: {groupId}]");
|
||||||
|
|
||||||
|
_logger.Information($"Deleted a group by id [group id: {groupId}]");
|
||||||
|
return RequestResult.Successful(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning($"Group Id does not exist [group id: {groupId}]");
|
||||||
|
return RequestResult.Failed("Something went wrong when updating the cache.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
36
Requests/DeleteGroupChatter.cs
Normal file
36
Requests/DeleteGroupChatter.cs
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class DeleteGroupChatter : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "delete_group_chatter";
|
||||||
|
public string[] RequiredKeys => ["chatter", "group"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public DeleteGroupChatter(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var chatterId = data["chatter"].ToString()!;
|
||||||
|
var groupId = data["group"].ToString()!;
|
||||||
|
|
||||||
|
if (!channel.Groups.Chatters.TryGetValue(groupId, out var chatters))
|
||||||
|
return Task.FromResult(RequestResult.Failed($"The group does not exist."));
|
||||||
|
|
||||||
|
var result = chatters.Remove(chatterId);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Deleted a group chatter by id [group id: {chatterId}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning($"Group Chatter Id does not exist [group id: {chatterId}]");
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
33
Requests/DeleteGroupPermission.cs
Normal file
33
Requests/DeleteGroupPermission.cs
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class DeleteGroupPermission : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "delete_group_permission";
|
||||||
|
public string[] RequiredKeys => ["id"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public DeleteGroupPermission(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = data["id"].ToString()!;
|
||||||
|
|
||||||
|
var permission = channel.GroupPermissions.Get(id);
|
||||||
|
var result = channel.GroupPermissions.Remove(id);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Deleted a group permission by id [group permission id: {id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(permission));
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning($"Group Permission Id does not exist [group permission id: {id}]");
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
31
Requests/DeletePolicy.cs
Normal file
31
Requests/DeletePolicy.cs
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class DeletePolicy : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "delete_policy";
|
||||||
|
public string[] RequiredKeys => ["id"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public DeletePolicy(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
string policyId = 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"]}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(policy.GroupId + "/" + policy.Path));
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning($"Failed to find policy by id [id: {policyId}]");
|
||||||
|
return Task.FromResult(RequestResult.Failed("Policy ID does not exist."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
32
Requests/DeleteRedeemableAction.cs
Normal file
32
Requests/DeleteRedeemableAction.cs
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class DeleteRedeemableAction : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "delete_redeemable_action";
|
||||||
|
public string[] RequiredKeys => ["name"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public DeleteRedeemableAction(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
string name = data["name"].ToString()!;
|
||||||
|
var result = channel.Actions.Remove(name);
|
||||||
|
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Deleted a redeemable action by name [name: {name}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning($"Action name does not exist [id: {name}]");
|
||||||
|
return Task.FromResult(RequestResult.Failed("Action name does not exist."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
32
Requests/DeleteRedemption.cs
Normal file
32
Requests/DeleteRedemption.cs
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class DeleteRedemption : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "delete_redemption";
|
||||||
|
public string[] RequiredKeys => ["id"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public DeleteRedemption(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
string id = data["id"].ToString()!;
|
||||||
|
var result = channel.Redemptions.Remove(id);
|
||||||
|
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Deleted a redemption by id [id: {id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning($"Redemption ID does not exist [id: {id}]");
|
||||||
|
return Task.FromResult(RequestResult.Failed("Redemption ID does not exist."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
32
Requests/DeleteTTSFilter.cs
Normal file
32
Requests/DeleteTTSFilter.cs
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
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 Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
string filterId = data["id"].ToString()!;
|
||||||
|
var result = channel.Filters.Remove(filterId);
|
||||||
|
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Deleted a TTS filter by id [tts filter id: {filterId}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning($"Filter ID does not exist [id: {filterId}]");
|
||||||
|
return Task.FromResult(RequestResult.Failed("Filter ID does not exist."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,3 +1,4 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
using HermesSocketServer.Models;
|
using HermesSocketServer.Models;
|
||||||
using HermesSocketServer.Store;
|
using HermesSocketServer.Store;
|
||||||
using ILogger = Serilog.ILogger;
|
using ILogger = Serilog.ILogger;
|
||||||
@ -8,20 +9,28 @@ namespace HermesSocketServer.Requests
|
|||||||
{
|
{
|
||||||
public string Name => "delete_tts_voice";
|
public string Name => "delete_tts_voice";
|
||||||
public string[] RequiredKeys => ["voice"];
|
public string[] RequiredKeys => ["voice"];
|
||||||
private IStore<string, Voice> _voices;
|
private IStore<string, TTSVoice> _voices;
|
||||||
private ILogger _logger;
|
private ILogger _logger;
|
||||||
|
|
||||||
public DeleteTTSVoice(VoiceStore voices, ILogger logger)
|
public DeleteTTSVoice(IStore<string, TTSVoice> voices, ILogger logger)
|
||||||
{
|
{
|
||||||
_voices = voices;
|
_voices = voices;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public 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"]}]");
|
var result = _voices.Remove(voiceId);
|
||||||
return RequestResult.Successful(null);
|
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Deleted a voice by id [voice id: {voiceId}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning($"Voice ID does not exist [id: {voiceId}]");
|
||||||
|
return Task.FromResult(RequestResult.Failed("Voice ID does not exist."));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -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,22 +7,18 @@ 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 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)));
|
return Task.FromResult(RequestResult.Successful(ids, notifyClientsOnAccount: false));
|
||||||
_logger.Information($"Fetched all chatters for channel [channel: {sender}]");
|
|
||||||
return RequestResult.Successful(ids, notifyClientsOnAccount: false);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,5 +1,5 @@
|
|||||||
using HermesSocketLibrary.db;
|
using HermesSocketServer.Models;
|
||||||
using HermesSocketLibrary.Socket.Data;
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
namespace HermesSocketServer.Requests
|
namespace HermesSocketServer.Requests
|
||||||
{
|
{
|
||||||
@ -7,35 +7,18 @@ namespace HermesSocketServer.Requests
|
|||||||
{
|
{
|
||||||
public string Name => "get_connections";
|
public string Name => "get_connections";
|
||||||
public string[] RequiredKeys => [];
|
public string[] RequiredKeys => [];
|
||||||
private Database _database;
|
private ILogger _logger;
|
||||||
private Serilog.ILogger _logger;
|
|
||||||
|
|
||||||
public GetConnections(Database database, Serilog.ILogger logger)
|
public GetConnections(ILogger logger)
|
||||||
{
|
{
|
||||||
_database = database;
|
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
{
|
{
|
||||||
var temp = new Dictionary<string, object>() { { "user", sender } };
|
var connections = channel.Connections.Get().Values;
|
||||||
|
_logger.Information($"Fetched all connections for channel [channel: {channel.Id}]");
|
||||||
var connections = new List<Connection>();
|
return Task.FromResult(RequestResult.Successful(connections, notifyClientsOnAccount: false));
|
||||||
string sql = "select \"name\", \"type\", \"clientId\", \"accessToken\", \"grantType\", \"scope\", \"expiresAt\", \"default\" from \"Connection\" where \"userId\" = @user";
|
|
||||||
await _database.Execute(sql, temp, sql =>
|
|
||||||
connections.Add(new Connection()
|
|
||||||
{
|
|
||||||
Name = sql.GetString(0),
|
|
||||||
Type = sql.GetString(1),
|
|
||||||
ClientId = sql.GetString(2),
|
|
||||||
AccessToken = sql.GetString(3),
|
|
||||||
GrantType = sql.GetString(4),
|
|
||||||
Scope = sql.GetString(5),
|
|
||||||
ExpiresAt = sql.GetDateTime(6),
|
|
||||||
Default = sql.GetBoolean(7)
|
|
||||||
})
|
|
||||||
);
|
|
||||||
return RequestResult.Successful(connections, false);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,3 +1,4 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
using HermesSocketServer.Store;
|
using HermesSocketServer.Store;
|
||||||
using ILogger = Serilog.ILogger;
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
@ -7,24 +8,24 @@ namespace HermesSocketServer.Requests
|
|||||||
{
|
{
|
||||||
public string Name => "get_default_tts_voice";
|
public string Name => "get_default_tts_voice";
|
||||||
public string[] RequiredKeys => [];
|
public string[] RequiredKeys => [];
|
||||||
private readonly UserStore _users;
|
private readonly IStore<string, User> _users;
|
||||||
private readonly ServerConfiguration _configuration;
|
private readonly ServerConfiguration _configuration;
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
public GetDefaultTTSVoice(UserStore users, ServerConfiguration configuration, ILogger logger)
|
public GetDefaultTTSVoice(IStore<string, User> users, ServerConfiguration configuration, ILogger logger)
|
||||||
{
|
{
|
||||||
_users = users;
|
_users = users;
|
||||||
_configuration = configuration;
|
_configuration = configuration;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public 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 Task.FromResult(RequestResult.Failed("Unable to find user data.", notifyClientsOnAccount: false));
|
||||||
|
|
||||||
return RequestResult.Successful(user.DefaultVoice ?? _configuration.Tts.DefaultTtsVoice, notifyClientsOnAccount: false);
|
return Task.FromResult(RequestResult.Successful(user.DefaultVoice ?? _configuration.Tts.DefaultTtsVoice, notifyClientsOnAccount: false));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
24
Requests/GetGroupPermissions.cs
Normal file
24
Requests/GetGroupPermissions.cs
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class GetGroupPermissions : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "get_group_permissions";
|
||||||
|
public string[] RequiredKeys => [];
|
||||||
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
|
public GetGroupPermissions(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var permissions = channel.GroupPermissions.Get().Values;
|
||||||
|
_logger.Information($"Fetched all group permissions for channel [channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(permissions, notifyClientsOnAccount: false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
37
Requests/GetGroups.cs
Normal file
37
Requests/GetGroups.cs
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class GetGroups : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "get_groups";
|
||||||
|
public string[] RequiredKeys => [];
|
||||||
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
|
public GetGroups(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var groups = channel.Groups.Get().Values;
|
||||||
|
var chatters = channel.Groups.Chatters;
|
||||||
|
var all = groups.Select(g => new GroupDetails()
|
||||||
|
{
|
||||||
|
Group = g,
|
||||||
|
Chatters = chatters[g.Id].Get().Values,
|
||||||
|
});
|
||||||
|
_logger.Information($"Fetched all groups for channel [channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(all, notifyClientsOnAccount: false));
|
||||||
|
}
|
||||||
|
|
||||||
|
private class GroupDetails
|
||||||
|
{
|
||||||
|
public required Group Group { get; set; }
|
||||||
|
public required IEnumerable<GroupChatter> Chatters { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,5 +1,5 @@
|
|||||||
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
|
||||||
@ -8,54 +8,27 @@ namespace HermesSocketServer.Requests
|
|||||||
{
|
{
|
||||||
public string Name => "get_permissions";
|
public string Name => "get_permissions";
|
||||||
public string[] RequiredKeys => [];
|
public string[] RequiredKeys => [];
|
||||||
private readonly Database _database;
|
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
public GetPermissions(Database database, ILogger logger)
|
public GetPermissions(ILogger logger)
|
||||||
{
|
{
|
||||||
_database = database;
|
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
{
|
{
|
||||||
var temp = new Dictionary<string, object>() { { "user", sender } };
|
var groups = channel.Groups.Get().Values;
|
||||||
|
var groupChatters = channel.Groups.Chatters.Values.SelectMany(g => g.Get().Values);
|
||||||
var groups = new List<Group>();
|
var groupPermissions = channel.GroupPermissions.Get().Values;
|
||||||
string sql = $"SELECT id, name, priority FROM \"Group\" WHERE \"userId\" = @user";
|
_logger.Information($"Fetched all permissions for channel [channel: {channel.Id}]");
|
||||||
await _database.Execute(sql, temp, (r) => groups.Add(new Group()
|
|
||||||
{
|
|
||||||
Id = r.GetGuid(0).ToString("D"),
|
|
||||||
Name = r.GetString(1),
|
|
||||||
Priority = r.GetInt32(2)
|
|
||||||
}));
|
|
||||||
|
|
||||||
var groupChatters = new List<GroupChatter>();
|
|
||||||
sql = $"SELECT \"groupId\", \"chatterId\", \"chatterId\" FROM \"ChatterGroup\" WHERE \"userId\" = @user";
|
|
||||||
await _database.Execute(sql, temp, (r) => groupChatters.Add(new GroupChatter()
|
|
||||||
{
|
|
||||||
GroupId = r.GetGuid(0).ToString("D"),
|
|
||||||
ChatterId = r.GetInt32(1)
|
|
||||||
}));
|
|
||||||
|
|
||||||
var groupPermissions = new List<GroupPermission>();
|
|
||||||
sql = $"SELECT id, \"groupId\", \"path\", \"allow\" FROM \"GroupPermission\" WHERE \"userId\" = @user";
|
|
||||||
await _database.Execute(sql, temp, (r) => groupPermissions.Add(new GroupPermission()
|
|
||||||
{
|
|
||||||
Id = r.GetGuid(0).ToString("D"),
|
|
||||||
GroupId = r.GetGuid(1).ToString("D"),
|
|
||||||
Path = r.GetString(2),
|
|
||||||
Allow = r.GetBoolean(3)
|
|
||||||
}));
|
|
||||||
_logger.Information($"Fetched all redemptions for channel [channel: {sender}]");
|
|
||||||
|
|
||||||
var info = new GroupInfo()
|
var info = new GroupInfo()
|
||||||
{
|
{
|
||||||
Groups = groups,
|
Groups = groups,
|
||||||
GroupChatters = groupChatters,
|
GroupChatters = groupChatters,
|
||||||
GroupPermissions = groupPermissions
|
GroupPermissions = groupPermissions,
|
||||||
};
|
};
|
||||||
return RequestResult.Successful(info, notifyClientsOnAccount: false);
|
return Task.FromResult(RequestResult.Successful(info, notifyClientsOnAccount: false));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
25
Requests/GetPolicies.cs
Normal file
25
Requests/GetPolicies.cs
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class GetPolicies : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "get_policies";
|
||||||
|
public string[] RequiredKeys => [];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public GetPolicies(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var results = channel.Policies.Get().Values;
|
||||||
|
|
||||||
|
_logger.Information($"Fetched policies for channel [policy size: {results.Count}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(results, notifyClientsOnAccount: false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,4 @@
|
|||||||
using System.Text.Json;
|
using HermesSocketServer.Models;
|
||||||
using HermesSocketLibrary.db;
|
|
||||||
using HermesSocketLibrary.Requests.Messages;
|
|
||||||
using ILogger = Serilog.ILogger;
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
namespace HermesSocketServer.Requests
|
namespace HermesSocketServer.Requests
|
||||||
@ -9,31 +7,18 @@ namespace HermesSocketServer.Requests
|
|||||||
{
|
{
|
||||||
public string Name => "get_redeemable_actions";
|
public string Name => "get_redeemable_actions";
|
||||||
public string[] RequiredKeys => [];
|
public string[] RequiredKeys => [];
|
||||||
private readonly JsonSerializerOptions _options;
|
|
||||||
private readonly Database _database;
|
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
public GetRedeemableActions(JsonSerializerOptions options, Database database, ILogger logger)
|
public GetRedeemableActions(ILogger logger)
|
||||||
{
|
{
|
||||||
_options = options;
|
|
||||||
_database = database;
|
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
{
|
{
|
||||||
var temp = new Dictionary<string, object>() { { "user", sender } };
|
var redemptions = channel.Actions.Get().Values;
|
||||||
|
_logger.Information($"Fetched all chatters' selected tts voice for channel [channel: {channel.Id}]");
|
||||||
var redemptions = new List<RedeemableAction>();
|
return Task.FromResult(RequestResult.Successful(redemptions, notifyClientsOnAccount: false));
|
||||||
string sql = $"SELECT name, type, data FROM \"Action\" WHERE \"userId\" = @user";
|
|
||||||
await _database.Execute(sql, temp, (r) => redemptions.Add(new RedeemableAction()
|
|
||||||
{
|
|
||||||
Name = r.GetString(0),
|
|
||||||
Type = r.GetString(1),
|
|
||||||
Data = JsonSerializer.Deserialize<IDictionary<string, string>>(r.GetString(2), _options)!
|
|
||||||
}));
|
|
||||||
_logger.Information($"Fetched all chatters' selected tts voice for channel [channel: {sender}]");
|
|
||||||
return RequestResult.Successful(redemptions, notifyClientsOnAccount: false);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,5 +1,5 @@
|
|||||||
using HermesSocketLibrary.db;
|
using HermesSocketLibrary.db;
|
||||||
using HermesSocketLibrary.Requests.Messages;
|
using HermesSocketServer.Models;
|
||||||
using ILogger = Serilog.ILogger;
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
namespace HermesSocketServer.Requests
|
namespace HermesSocketServer.Requests
|
||||||
@ -17,11 +17,11 @@ namespace HermesSocketServer.Requests
|
|||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public 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 = channel.Redemptions.Get().Values; /* 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";
|
||||||
await _database.Execute(sql, temp, (r) => redemptions.Add(new Redemption()
|
await _database.Execute(sql, temp, (r) => redemptions.Add(new Redemption()
|
||||||
{
|
{
|
||||||
@ -30,9 +30,9 @@ namespace HermesSocketServer.Requests
|
|||||||
ActionName = r.GetString(2),
|
ActionName = r.GetString(2),
|
||||||
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 Task.FromResult(RequestResult.Successful(redemptions, notifyClientsOnAccount: false));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -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_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 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 Task.FromResult(RequestResult.Successful(results, notifyClientsOnAccount: false));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -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;
|
||||||
|
|
||||||
@ -8,25 +9,25 @@ namespace HermesSocketServer.Requests
|
|||||||
{
|
{
|
||||||
public string Name => "get_tts_voices";
|
public string Name => "get_tts_voices";
|
||||||
public string[] RequiredKeys => [];
|
public string[] RequiredKeys => [];
|
||||||
private VoiceStore _voices;
|
private IStore<string, TTSVoice> _voices;
|
||||||
private ILogger _logger;
|
private ILogger _logger;
|
||||||
|
|
||||||
public GetTTSVoices(VoiceStore voices, ILogger logger)
|
public GetTTSVoices(IStore<string, TTSVoice> voices, ILogger logger)
|
||||||
{
|
{
|
||||||
_voices = voices;
|
_voices = voices;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
{
|
{
|
||||||
IEnumerable<VoiceDetails> voices = _voices.Get().Select(v => new VoiceDetails()
|
IEnumerable<TTSVoice> voices = _voices.Get().Select(v => new TTSVoice()
|
||||||
{
|
{
|
||||||
Id = v.Value.Id,
|
Id = v.Value.Id,
|
||||||
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 Task.FromResult(RequestResult.Successful(voices, notifyClientsOnAccount: false));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,5 +1,5 @@
|
|||||||
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
|
||||||
@ -8,29 +8,19 @@ 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 ILogger _logger;
|
||||||
private readonly ILogger _logger;
|
|
||||||
|
|
||||||
public GetTTSWordFilters(Database database, ILogger logger)
|
public GetTTSWordFilters(ILogger logger)
|
||||||
{
|
{
|
||||||
_database = database;
|
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public 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";
|
return Task.FromResult(RequestResult.Successful(filters, notifyClientsOnAccount: false));
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -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);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,6 +1,5 @@
|
|||||||
using HermesSocketLibrary.Socket.Data;
|
using HermesSocketLibrary.Socket.Data;
|
||||||
using HermesSocketServer.Services;
|
using HermesSocketServer.Services;
|
||||||
using Serilog;
|
|
||||||
|
|
||||||
namespace HermesSocketServer.Requests
|
namespace HermesSocketServer.Requests
|
||||||
{
|
{
|
||||||
@ -21,11 +20,17 @@ namespace HermesSocketServer.Requests
|
|||||||
public async Task<RequestResult> Grant(string sender, RequestMessage? message)
|
public async Task<RequestResult> Grant(string sender, RequestMessage? message)
|
||||||
{
|
{
|
||||||
if (message == null || message.Type == null)
|
if (message == null || message.Type == null)
|
||||||
|
{
|
||||||
|
_logger.Debug($"Request type does not exist [id: {message?.RequestId ?? "null"}][nounce: {message?.Nounce ?? "null"}]");
|
||||||
return RequestResult.Failed("Request type does not exist.");
|
return RequestResult.Failed("Request type does not exist.");
|
||||||
|
}
|
||||||
|
|
||||||
var channel = _channels.Get(sender);
|
var channel = _channels.Get(sender);
|
||||||
if (channel == null)
|
if (channel == null)
|
||||||
|
{
|
||||||
|
_logger.Debug($"Channel does not exist [id: {message.RequestId}][nounce: {message.Nounce}]");
|
||||||
return RequestResult.Failed("Channel does not exist.");
|
return RequestResult.Failed("Channel does not exist.");
|
||||||
|
}
|
||||||
|
|
||||||
if (!_requests.TryGetValue(message.Type, out IRequest? request) || request == null)
|
if (!_requests.TryGetValue(message.Type, out IRequest? request) || request == null)
|
||||||
{
|
{
|
||||||
@ -36,18 +41,24 @@ namespace HermesSocketServer.Requests
|
|||||||
if (request.RequiredKeys.Any())
|
if (request.RequiredKeys.Any())
|
||||||
{
|
{
|
||||||
if (message.Data == null)
|
if (message.Data == null)
|
||||||
|
{
|
||||||
|
_logger.Debug($"Request is lacking data entries [id: {message.RequestId}][nounce: {message.Nounce}]");
|
||||||
return RequestResult.Failed($"Request is lacking data entries.");
|
return RequestResult.Failed($"Request is lacking data entries.");
|
||||||
|
}
|
||||||
|
|
||||||
foreach (var key in request.RequiredKeys)
|
foreach (var key in request.RequiredKeys)
|
||||||
{
|
{
|
||||||
if (!message.Data.ContainsKey(key))
|
if (!message.Data.ContainsKey(key))
|
||||||
|
{
|
||||||
|
_logger.Debug($"Request is missing '{key}' in its data entries [id: {message.RequestId}][nounce: {message.Nounce}]");
|
||||||
return RequestResult.Failed($"Request is missing '{key}' in its data entries.");
|
return RequestResult.Failed($"Request is missing '{key}' in its data entries.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return await request.Grant(sender, message.Data);
|
return await request.Grant(channel, message.Data ?? new Dictionary<string, object>());
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
|
@ -15,12 +15,12 @@ namespace HermesSocketServer.Requests
|
|||||||
|
|
||||||
public static RequestResult Successful(object? result, bool notifyClientsOnAccount = true)
|
public static RequestResult Successful(object? result, bool notifyClientsOnAccount = true)
|
||||||
{
|
{
|
||||||
return RequestResult.Successful(result, notifyClientsOnAccount);
|
return new RequestResult(true, result, notifyClientsOnAccount);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static RequestResult Failed(string error, bool notifyClientsOnAccount = true)
|
public static RequestResult Failed(string error, bool notifyClientsOnAccount = true)
|
||||||
{
|
{
|
||||||
return RequestResult.Successful(error, notifyClientsOnAccount);
|
return new RequestResult(false, error, notifyClientsOnAccount);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
50
Requests/UpdateConnection.cs
Normal file
50
Requests/UpdateConnection.cs
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
using HermesSocketLibrary.Socket.Data;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class UpdateConnection : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "update_connection";
|
||||||
|
public string[] RequiredKeys => ["name", "type", "clientId", "accessToken", "grantType", "scope", "expiration"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public UpdateConnection(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
string name = data["name"].ToString()!;
|
||||||
|
string type = data["type"].ToString()!;
|
||||||
|
string clientId = data["clientId"].ToString()!;
|
||||||
|
string accessToken = data["accessToken"].ToString()!;
|
||||||
|
string grantType = data["grantType"].ToString()!;
|
||||||
|
string scope = data["scope"].ToString()!;
|
||||||
|
if (!DateTime.TryParse(data["expiration"].ToString()!, out var expiresAt))
|
||||||
|
return Task.FromResult(RequestResult.Failed("Expiration needs to be a date time string."));
|
||||||
|
|
||||||
|
var connection = new Connection()
|
||||||
|
{
|
||||||
|
UserId = channel.Id,
|
||||||
|
Name = name,
|
||||||
|
Type = type,
|
||||||
|
ClientId = clientId,
|
||||||
|
AccessToken = accessToken,
|
||||||
|
GrantType = grantType,
|
||||||
|
Scope = scope,
|
||||||
|
ExpiresAt = expiresAt,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool result = channel.Connections.Modify(name, connection);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Added connection to channel [name: {name}][type: {type}][scope: {scope}][expiration: {expiresAt}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(connection));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,3 +1,4 @@
|
|||||||
|
using HermesSocketServer.Models;
|
||||||
using HermesSocketServer.Store;
|
using HermesSocketServer.Store;
|
||||||
using ILogger = Serilog.ILogger;
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
@ -7,26 +8,26 @@ namespace HermesSocketServer.Requests
|
|||||||
{
|
{
|
||||||
public string Name => "update_default_tts_voice";
|
public string Name => "update_default_tts_voice";
|
||||||
public string[] RequiredKeys => ["user", "voice"];
|
public string[] RequiredKeys => ["user", "voice"];
|
||||||
private UserStore _users;
|
private IStore<string, User> _users;
|
||||||
private ILogger _logger;
|
private ILogger _logger;
|
||||||
|
|
||||||
public UpdateDefaultTTSVoice(UserStore users, ILogger logger)
|
public UpdateDefaultTTSVoice(IStore<string, User> users, ILogger logger)
|
||||||
{
|
{
|
||||||
_users = users;
|
_users = users;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public 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 Task.FromResult(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 Task.FromResult(RequestResult.Successful(null));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
42
Requests/UpdateGroup.cs
Normal file
42
Requests/UpdateGroup.cs
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class UpdateGroup : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "update_group";
|
||||||
|
public string[] RequiredKeys => ["id", "name", "priority"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public UpdateGroup(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = data["id"].ToString()!;
|
||||||
|
string name = data["name"].ToString()!;
|
||||||
|
if (!int.TryParse(data["priority"].ToString()!, out var priority))
|
||||||
|
return Task.FromResult(RequestResult.Failed("Priority needs to be an integer."));
|
||||||
|
|
||||||
|
var group = new Group()
|
||||||
|
{
|
||||||
|
Id = id,
|
||||||
|
UserId = channel.Id,
|
||||||
|
Name = name,
|
||||||
|
Priority = priority,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool result = channel.Groups.Modify(id, group);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Updated group on channel [group id: {id}][name: {name}][priority: {priority}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(group));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
46
Requests/UpdateGroupChatter.cs
Normal file
46
Requests/UpdateGroupChatter.cs
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class UpdateGroupChatter : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "update_group_chatter";
|
||||||
|
public string[] RequiredKeys => ["group", "chatter", "label"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public UpdateGroupChatter(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = Guid.NewGuid();
|
||||||
|
string groupId = data["group"].ToString()!;
|
||||||
|
if (!int.TryParse(data["chatter"].ToString()!, out var chatterId))
|
||||||
|
return Task.FromResult(RequestResult.Failed("Chatter Id needs to be an integer."));
|
||||||
|
string chatterLabel = data["label"].ToString()!;
|
||||||
|
|
||||||
|
var groupChatter = new GroupChatter()
|
||||||
|
{
|
||||||
|
UserId = channel.Id,
|
||||||
|
GroupId = groupId,
|
||||||
|
ChatterId = chatterId,
|
||||||
|
ChatterLabel = chatterLabel,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!channel.Groups.Chatters.TryGetValue(groupId, out var chatters))
|
||||||
|
return Task.FromResult(RequestResult.Failed($"The group does not exist."));
|
||||||
|
|
||||||
|
bool result = chatters.Modify(chatterId.ToString(), groupChatter);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Updated group chatter on channel [group id: {id}][group id: {groupId}][chatter id: {chatterId}][chatter label: {chatterLabel}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(groupChatter));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
48
Requests/UpdateGroupPermission.cs
Normal file
48
Requests/UpdateGroupPermission.cs
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class UpdateGroupPermission : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "update_group_permission";
|
||||||
|
public string[] RequiredKeys => ["id", "group", "path", "allow"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public UpdateGroupPermission(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = data["id"].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;
|
||||||
|
|
||||||
|
var permission = new GroupPermission()
|
||||||
|
{
|
||||||
|
Id = id.ToString(),
|
||||||
|
UserId = channel.Id,
|
||||||
|
GroupId = groupId,
|
||||||
|
Path = path,
|
||||||
|
Allow = allow,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!channel.GroupPermissions.Get().Values.Any(p => p.GroupId == groupId && p.Path == path))
|
||||||
|
{
|
||||||
|
return Task.FromResult(RequestResult.Failed("Permission does not exist."));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool result = channel.GroupPermissions.Modify(id.ToString(), permission);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Updated group permission on channel [permission id: {id}][group id: {groupId}][path: {path}][allow: {allow}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(permission));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
45
Requests/UpdatePolicy.cs
Normal file
45
Requests/UpdatePolicy.cs
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
using HermesSocketServer.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class UpdatePolicy : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "update_policy";
|
||||||
|
public string[] RequiredKeys => ["id", "groupId", "path", "count", "span"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public UpdatePolicy(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = Guid.Parse(data["id"].ToString()!);
|
||||||
|
string groupId = data["groupId"].ToString()!;
|
||||||
|
string path = data["path"].ToString()!;
|
||||||
|
int count = int.Parse(data["count"].ToString()!);
|
||||||
|
int span = int.Parse(data["span"].ToString()!);
|
||||||
|
|
||||||
|
var policy = new Policy()
|
||||||
|
{
|
||||||
|
Id = id,
|
||||||
|
UserId = channel.Id,
|
||||||
|
GroupId = Guid.Parse(groupId),
|
||||||
|
Path = path,
|
||||||
|
Usage = count,
|
||||||
|
Span = span,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool result = channel.Policies.Modify(id.ToString(), policy);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Updated policy on channel [policy id: {id}][group id: {groupId}][path: {path}][count: {count}][span: {span}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(policy));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
57
Requests/UpdateRedeemableAction.cs
Normal file
57
Requests/UpdateRedeemableAction.cs
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class UpdateRedeemableAction : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "update_redeemable_action";
|
||||||
|
public string[] RequiredKeys => ["name", "data", "type"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public UpdateRedeemableAction(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
string name = data["name"].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
|
||||||
|
{
|
||||||
|
dict = JsonSerializer.Deserialize<IDictionary<string, string>>(d)!;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_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."));
|
||||||
|
}
|
||||||
|
|
||||||
|
var action = new RedeemableAction()
|
||||||
|
{
|
||||||
|
UserId = channel.Id,
|
||||||
|
Name = name,
|
||||||
|
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}][has message: {hasMessage}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(action));
|
||||||
|
}
|
||||||
|
if (channel.Actions.Get(name) == null)
|
||||||
|
return Task.FromResult(RequestResult.Failed("Action does not exist."));
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
47
Requests/UpdateRedemption.cs
Normal file
47
Requests/UpdateRedemption.cs
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Requests
|
||||||
|
{
|
||||||
|
public class UpdateRedemption : IRequest
|
||||||
|
{
|
||||||
|
public string Name => "update_redemption";
|
||||||
|
public string[] RequiredKeys => ["id", "redemption", "action", "order", "state"];
|
||||||
|
private ILogger _logger;
|
||||||
|
|
||||||
|
public UpdateRedemption(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = data["id"].ToString()!;
|
||||||
|
string redemptionId = data["redemption"].ToString()!;
|
||||||
|
string actionName = data["action"].ToString()!;
|
||||||
|
if (channel.Actions.Get(actionName) == null)
|
||||||
|
return Task.FromResult(RequestResult.Failed("Action Name must be an existing action."));
|
||||||
|
if (!int.TryParse(data["order"].ToString()!, out var order))
|
||||||
|
return Task.FromResult(RequestResult.Failed("Order must be an integer."));
|
||||||
|
bool state = data["state"].ToString()?.ToLower() == "true";
|
||||||
|
|
||||||
|
Redemption redemption = new Redemption() {
|
||||||
|
Id = id,
|
||||||
|
UserId = channel.Id,
|
||||||
|
RedemptionId = redemptionId,
|
||||||
|
ActionName = actionName,
|
||||||
|
Order = order,
|
||||||
|
State = state,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool result = channel.Redemptions.Modify(id, redemption);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Updated redemption on channel [id: {id}][redemption id: {redemptionId}][action: {actionName}][order: {order}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(redemption));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
47
Requests/UpdateTTSFilter.cs
Normal file
47
Requests/UpdateTTSFilter.cs
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
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 ILogger _logger;
|
||||||
|
|
||||||
|
public UpdateTTSFilter(ILogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
|
{
|
||||||
|
var id = data["id"].ToString()!;
|
||||||
|
string search = data["search"].ToString()!;
|
||||||
|
string replace = data["replace"].ToString()!;
|
||||||
|
int flag = -1;
|
||||||
|
if (data.TryGetValue("flag", out var flagObject)) {
|
||||||
|
int.TryParse(flagObject.ToString(), out flag);
|
||||||
|
}
|
||||||
|
|
||||||
|
var filter = new TTSWordFilter()
|
||||||
|
{
|
||||||
|
Id = id,
|
||||||
|
UserId = channel.Id,
|
||||||
|
Search = search,
|
||||||
|
Replace = replace,
|
||||||
|
Flag = flag,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool result = channel.Filters.Modify(id, filter);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_logger.Information($"Updated filter on channel [filter id: {id}][search: {search}][replace: {replace}][channel: {channel.Id}]");
|
||||||
|
return Task.FromResult(RequestResult.Successful(filter));
|
||||||
|
}
|
||||||
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,4 @@
|
|||||||
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,43 +7,42 @@ namespace HermesSocketServer.Requests
|
|||||||
{
|
{
|
||||||
public string Name => "update_tts_user";
|
public string Name => "update_tts_user";
|
||||||
public string[] RequiredKeys => ["chatter", "voice"];
|
public string[] RequiredKeys => ["chatter", "voice"];
|
||||||
private ChannelManager _channels;
|
|
||||||
private Database _database;
|
|
||||||
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(ServerConfiguration configuration, ILogger logger)
|
||||||
{
|
{
|
||||||
_database = database;
|
|
||||||
_channels = channels;
|
|
||||||
_configuration = configuration;
|
_configuration = configuration;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public 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;
|
return Task.FromResult(RequestResult.Failed("Invalid Twitch user id."));
|
||||||
data["voice"] = data["voice"].ToString();
|
|
||||||
|
|
||||||
var check = await _database.ExecuteScalar("SELECT state FROM \"TtsVoiceState\" WHERE \"userId\" = @user AND \"ttsVoiceId\" = @voice", data) ?? false;
|
data["user"] = channel.Id;
|
||||||
if ((check is not bool state || !state) && chatterId != _configuration.Tts.OwnerId)
|
var voiceId = data["voice"].ToString()!;
|
||||||
return RequestResult.Failed("Voice is either non-existent or disabled on this channel.");
|
|
||||||
|
|
||||||
var channel = _channels.Get(sender);
|
var check = channel.VoiceStates.Get(voiceId)?.Enabled ?? false;
|
||||||
var result = channel.Chatters.Set(chatterId.ToString(), new ChatterVoice()
|
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()
|
||||||
{
|
{
|
||||||
UserId = sender,
|
UserId = channel.Id,
|
||||||
ChatterId = chatterId.ToString(),
|
ChatterId = chatterId,
|
||||||
VoiceId = data["voice"].ToString()!
|
VoiceId = voiceId
|
||||||
});
|
};
|
||||||
|
|
||||||
|
var result = channel.Chatters.Modify(chatterId.ToString(), voice);
|
||||||
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 selected tts voice on channel [chatter id: {chatterId}][voice id: {voiceId}][channel: {channel.Id}]");
|
||||||
return RequestResult.Successful(null);
|
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."));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,3 +1,4 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
using HermesSocketServer.Models;
|
using HermesSocketServer.Models;
|
||||||
using HermesSocketServer.Store;
|
using HermesSocketServer.Store;
|
||||||
using ILogger = Serilog.ILogger;
|
using ILogger = Serilog.ILogger;
|
||||||
@ -8,31 +9,33 @@ namespace HermesSocketServer.Requests
|
|||||||
{
|
{
|
||||||
public string Name => "update_tts_voice";
|
public string Name => "update_tts_voice";
|
||||||
public string[] RequiredKeys => ["voice", "voiceId"];
|
public string[] RequiredKeys => ["voice", "voiceId"];
|
||||||
private IStore<string, Voice> _voices;
|
private IStore<string, TTSVoice> _voices;
|
||||||
private ILogger _logger;
|
private ILogger _logger;
|
||||||
|
|
||||||
public UpdateTTSVoice(VoiceStore voices, ILogger logger)
|
public UpdateTTSVoice(IStore<string, TTSVoice> voices, ILogger logger)
|
||||||
{
|
{
|
||||||
_voices = voices;
|
_voices = voices;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public 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 voice = new TTSVoice()
|
||||||
{
|
{
|
||||||
Id = data["voiceid"].ToString()!,
|
Id = voiceId,
|
||||||
Name = data["voice"].ToString()!
|
Name = voiceName
|
||||||
});
|
};
|
||||||
|
|
||||||
|
var result = _voices.Modify(voiceId, voice);
|
||||||
if (result)
|
if (result)
|
||||||
{
|
{
|
||||||
_logger.Information($"Updated voice's [voice id: {data["voiceid"]}] name [new name: {data["voice"]}]");
|
_logger.Information($"Updated voice's name on channel [voice id: {voiceId}][name: {voiceName}][channel: {channel.Id}]");
|
||||||
return RequestResult.Successful(null);
|
return Task.FromResult(RequestResult.Successful(voice));
|
||||||
}
|
}
|
||||||
return RequestResult.Failed("Something went wrong when updating the cache.");
|
return Task.FromResult(RequestResult.Failed("Something went wrong when updating the cache."));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,4 +1,6 @@
|
|||||||
using HermesSocketLibrary.db;
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
using ILogger = Serilog.ILogger;
|
using ILogger = Serilog.ILogger;
|
||||||
|
|
||||||
namespace HermesSocketServer.Requests
|
namespace HermesSocketServer.Requests
|
||||||
@ -16,18 +18,25 @@ namespace HermesSocketServer.Requests
|
|||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestResult> Grant(string sender, IDictionary<string, object>? data)
|
public Task<RequestResult> Grant(Channel channel, IDictionary<string, object> data)
|
||||||
{
|
{
|
||||||
data["voice"] = data["voice"].ToString();
|
var voiceId = data["voice"].ToString()!;
|
||||||
data["state"] = data["state"].ToString() == "True";
|
var state = data["state"].ToString()?.ToLower() == "true";
|
||||||
data["user"] = sender;
|
|
||||||
|
|
||||||
string sql = "INSERT INTO \"TtsVoiceState\" (\"userId\", \"ttsVoiceId\", state) VALUES (@user, @voice, @state) ON CONFLICT (\"userId\", \"ttsVoiceId\") DO UPDATE SET state = @state";
|
var voiceState = new TTSVoiceState()
|
||||||
var result = await _database.Execute(sql, data);
|
{
|
||||||
_logger.Information($"Updated voice's [voice id: {data["voice"]}] state [new state: {data["state"]}][channel: {data["user"]}]");
|
Id = voiceId,
|
||||||
if (result > 0)
|
UserId = channel.Id,
|
||||||
return RequestResult.Successful(null);
|
Enabled = state,
|
||||||
return RequestResult.Failed("Something went wrong when updating the database.");
|
};
|
||||||
|
|
||||||
|
var result = channel.VoiceStates.Set(voiceId, voiceState);
|
||||||
|
if (result)
|
||||||
|
{
|
||||||
|
_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."));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
105
Server.cs
105
Server.cs
@ -32,7 +32,7 @@ namespace HermesSocketLibrary
|
|||||||
|
|
||||||
public async Task Handle(WebSocketUser socket, HttpContext context)
|
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);
|
_sockets.Add(socket);
|
||||||
var buffer = new byte[1024 * 8];
|
var buffer = new byte[1024 * 8];
|
||||||
|
|
||||||
@ -44,68 +44,51 @@ namespace HermesSocketLibrary
|
|||||||
if (result == null || result.MessageType == WebSocketMessageType.Close || !socket.Connected)
|
if (result == null || result.MessageType == WebSocketMessageType.Close || !socket.Connected)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
string message = Encoding.UTF8.GetString(buffer, 0, result.Count).TrimEnd('\0');
|
string messageString = Encoding.UTF8.GetString(buffer, 0, result.Count).TrimEnd('\0');
|
||||||
var obj = JsonSerializer.Deserialize<WebSocketMessage>(message, _options);
|
var message = JsonSerializer.Deserialize<WebSocketMessage>(messageString, _options);
|
||||||
if (obj == null)
|
if (message == null)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
if (obj.OpCode != 0)
|
if (message.OpCode != 0)
|
||||||
_logger.Information($"rxm: {message} [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.UID}]");
|
_logger.Information($"receive: {messageString} [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.SessionId}]");
|
||||||
|
|
||||||
int[] nonProtectedOps = { 0, 1 };
|
if (message.OpCode < 0 || message.OpCode > 8 || message.OpCode == 2 || message.OpCode == 4)
|
||||||
if (string.IsNullOrEmpty(socket.Id) && !nonProtectedOps.Contains(obj.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.UID}]");
|
await socket.Send(5, new LoggingMessage("Received an invalid message: " + messageString, HermesLoggingLevel.Error));
|
||||||
return;
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
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}]");
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
int[] protectedOps = { 0, 3, 5, 6, 7, 8 };
|
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;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
if (message.Data == null)
|
||||||
* 0: Heartbeat
|
|
||||||
* 1: Login RX
|
|
||||||
* 2: Login Ack TX
|
|
||||||
* 3: Request RX
|
|
||||||
* 4: Request Ack TX
|
|
||||||
* 5: Logging RX/TX
|
|
||||||
*/
|
|
||||||
if (obj.Data == null)
|
|
||||||
{
|
{
|
||||||
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 = message.Data.ToString()!;
|
||||||
else if (obj.OpCode == 1)
|
message.Data = DeserializeData(message.OpCode, data);
|
||||||
obj.Data = JsonSerializer.Deserialize<HermesLoginMessage>(obj.Data.ToString(), _options);
|
await _handlers.Execute(socket, message.OpCode, message.Data);
|
||||||
else if (obj.OpCode == 3)
|
|
||||||
obj.Data = JsonSerializer.Deserialize<RequestMessage>(obj.Data.ToString(), _options);
|
|
||||||
else if (obj.OpCode == 5)
|
|
||||||
obj.Data = JsonSerializer.Deserialize<LoggingMessage>(obj.Data.ToString(), _options);
|
|
||||||
else if (obj.OpCode == 6)
|
|
||||||
obj.Data = JsonSerializer.Deserialize<ChatterMessage>(obj.Data.ToString(), _options);
|
|
||||||
else if (obj.OpCode == 7)
|
|
||||||
obj.Data = JsonSerializer.Deserialize<EmoteDetailsMessage>(obj.Data.ToString(), _options);
|
|
||||||
else if (obj.OpCode == 8)
|
|
||||||
obj.Data = JsonSerializer.Deserialize<EmoteUsageMessage>(obj.Data.ToString(), _options);
|
|
||||||
else
|
|
||||||
{
|
|
||||||
await socket.Send(5, new LoggingMessage("Received an invalid message: " + message, HermesLoggingLevel.Error));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
await _handlers.Execute(socket, obj.OpCode, obj.Data);
|
|
||||||
}
|
}
|
||||||
catch (WebSocketException wse)
|
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)
|
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}]");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,14 +99,44 @@ namespace HermesSocketLibrary
|
|||||||
}
|
}
|
||||||
catch (Exception e)
|
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.Warning(e, $"Client failed to disconnect [ip: {socket.IPAddress}][id: {socket.Id}][name: {socket.Name}][token: {socket.ApiKey}][uid: {socket.SessionId}]");
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
socket.Dispose();
|
socket.Dispose();
|
||||||
_sockets.Remove(socket);
|
_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.
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private object? DeserializeData(int opcode, string data)
|
||||||
|
{
|
||||||
|
if (opcode == 0)
|
||||||
|
return JsonSerializer.Deserialize<HeartbeatMessage>(data, _options);
|
||||||
|
else if (opcode == 1)
|
||||||
|
return JsonSerializer.Deserialize<HermesLoginMessage>(data, _options);
|
||||||
|
else if (opcode == 3)
|
||||||
|
return JsonSerializer.Deserialize<RequestMessage>(data, _options);
|
||||||
|
else if (opcode == 5)
|
||||||
|
return JsonSerializer.Deserialize<LoggingMessage>(data, _options);
|
||||||
|
else if (opcode == 6)
|
||||||
|
return JsonSerializer.Deserialize<ChatterMessage>(data, _options);
|
||||||
|
else if (opcode == 7)
|
||||||
|
return JsonSerializer.Deserialize<EmoteDetailsMessage>(data, _options);
|
||||||
|
else if (opcode == 8)
|
||||||
|
return JsonSerializer.Deserialize<EmoteUsageMessage>(data, _options);
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,29 +1,32 @@
|
|||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
namespace HermesSocketServer
|
namespace HermesSocketServer
|
||||||
{
|
{
|
||||||
public class ServerConfiguration
|
public class ServerConfiguration
|
||||||
{
|
{
|
||||||
public string Environment;
|
public required string Environment;
|
||||||
public WebsocketServerConfiguration WebsocketServer;
|
public required WebsocketServerConfiguration WebsocketServer;
|
||||||
public DatabaseConfiguration Database;
|
public required DatabaseConfiguration Database;
|
||||||
public TTSConfiguration Tts;
|
public required TTSConfiguration Tts;
|
||||||
public string AdminPassword;
|
public string? AdminPassword;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class WebsocketServerConfiguration
|
public class WebsocketServerConfiguration
|
||||||
{
|
{
|
||||||
public string Host;
|
public required string Host;
|
||||||
public string Port;
|
public required string Port;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class DatabaseConfiguration
|
public class DatabaseConfiguration
|
||||||
{
|
{
|
||||||
public string ConnectionString;
|
public required string ConnectionString;
|
||||||
public int SaveDelayInSeconds;
|
public int SaveDelayInSeconds;
|
||||||
|
public required IDictionary<string, DatabaseTable> Tables;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class TTSConfiguration
|
public class TTSConfiguration
|
||||||
{
|
{
|
||||||
public long OwnerId;
|
public long OwnerId;
|
||||||
public string DefaultTtsVoice;
|
public required string DefaultTtsVoice;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,5 +1,6 @@
|
|||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using HermesSocketLibrary.db;
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
using HermesSocketServer.Models;
|
using HermesSocketServer.Models;
|
||||||
using HermesSocketServer.Store;
|
using HermesSocketServer.Store;
|
||||||
|
|
||||||
@ -7,19 +8,23 @@ namespace HermesSocketServer.Services
|
|||||||
{
|
{
|
||||||
public class ChannelManager
|
public class ChannelManager
|
||||||
{
|
{
|
||||||
private readonly UserStore _users;
|
private readonly IStore<string, User> _users;
|
||||||
private readonly Database _database;
|
private readonly Database _database;
|
||||||
|
private readonly IStore<string, TTSVoice> _voices;
|
||||||
|
private readonly ServerConfiguration _configuration;
|
||||||
private readonly Serilog.ILogger _logger;
|
private readonly Serilog.ILogger _logger;
|
||||||
private readonly IDictionary<string, Channel> _channels;
|
private readonly IDictionary<string, Channel> _channels;
|
||||||
private readonly object _lock;
|
private readonly Mutex _mutex;
|
||||||
|
|
||||||
public ChannelManager(UserStore users, Database database, Serilog.ILogger logger)
|
public ChannelManager(IStore<string, User> users, Database database, IStore<string, TTSVoice> voices, ServerConfiguration configuration, Serilog.ILogger logger)
|
||||||
{
|
{
|
||||||
_users = users;
|
_users = users;
|
||||||
_database = database;
|
_database = database;
|
||||||
|
_voices = voices;
|
||||||
|
_configuration = configuration;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_channels = new ConcurrentDictionary<string, Channel>();
|
_channels = new ConcurrentDictionary<string, Channel>();
|
||||||
_lock = new object();
|
_mutex = new Mutex();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -27,54 +32,117 @@ namespace HermesSocketServer.Services
|
|||||||
{
|
{
|
||||||
var user = _users.Get(userId);
|
var user = _users.Get(userId);
|
||||||
if (user == null)
|
if (user == null)
|
||||||
{
|
|
||||||
return null;
|
return null;
|
||||||
}
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
if (_channels.ContainsKey(userId))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var chatters = new ChatterStore(userId, _database, _logger);
|
return await Task.Run(() =>
|
||||||
var policies = new PolicyStore(userId, _database, _logger);
|
{
|
||||||
await Task.WhenAll([
|
try
|
||||||
chatters.Load(),
|
{
|
||||||
policies.Load(),
|
_mutex.WaitOne();
|
||||||
]);
|
if (_channels.TryGetValue(userId, out var channel))
|
||||||
|
return channel;
|
||||||
|
|
||||||
var channel = new Channel()
|
var actionTable = _configuration.Database.Tables["Action"];
|
||||||
|
var chatterTable = _configuration.Database.Tables["Chatter"];
|
||||||
|
var connectionTable = _configuration.Database.Tables["Connection"];
|
||||||
|
var connectionStateTable = _configuration.Database.Tables["ConnectionState"];
|
||||||
|
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,
|
Id = userId,
|
||||||
User = user,
|
User = user,
|
||||||
Chatters = chatters,
|
Chatters = chatters,
|
||||||
Policies = policies
|
Connections = connections,
|
||||||
|
Groups = groups,
|
||||||
|
GroupPermissions = groupPermissions,
|
||||||
|
Policies = policies,
|
||||||
|
Filters = filters,
|
||||||
|
Actions = actions,
|
||||||
|
Redemptions = redemptions,
|
||||||
|
VoiceStates = voiceStates,
|
||||||
};
|
};
|
||||||
|
|
||||||
lock (_lock)
|
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);
|
_channels.Add(userId, channel);
|
||||||
}
|
|
||||||
return channel;
|
return channel;
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_mutex.ReleaseMutex();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
public Channel? Get(string channelId)
|
public Channel? Get(string channelId)
|
||||||
{
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_mutex.WaitOne();
|
||||||
if (_channels.TryGetValue(channelId, out var channel))
|
if (_channels.TryGetValue(channelId, out var channel))
|
||||||
return channel;
|
return channel;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_mutex.ReleaseMutex();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async Task Save(string userId)
|
public async Task Save(string userId)
|
||||||
{
|
{
|
||||||
if (!_channels.TryGetValue(userId, out var channel))
|
Channel? channel;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_mutex.WaitOne();
|
||||||
|
if (!_channels.TryGetValue(userId, out channel))
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_mutex.ReleaseMutex();
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Debug($"Saving channel data to database [channel id: {channel.Id}][channel name: {channel.User.Name}]");
|
||||||
await Task.WhenAll([
|
await Task.WhenAll([
|
||||||
channel.Chatters.Save(),
|
channel.Chatters.Save(),
|
||||||
|
channel.Connections.Save(),
|
||||||
|
channel.Groups.Save(),
|
||||||
|
channel.GroupPermissions.Save(),
|
||||||
channel.Policies.Save(),
|
channel.Policies.Save(),
|
||||||
|
channel.Filters.Save(),
|
||||||
|
channel.Actions.Save(),
|
||||||
|
channel.Redemptions.Save(),
|
||||||
|
channel.VoiceStates.Save(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -83,10 +151,25 @@ namespace HermesSocketServer.Services
|
|||||||
foreach (var channel in _channels.Values)
|
foreach (var channel in _channels.Values)
|
||||||
{
|
{
|
||||||
_logger.Debug($"Saving channel data to database [channel id: {channel.Id}][channel name: {channel.User.Name}]");
|
_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.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.Policies.Save(),
|
||||||
]);
|
channel.Redemptions.Save(),
|
||||||
|
]).ConfigureAwait(false);
|
||||||
|
|
||||||
|
await genericTablesTask;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
using HermesSocketServer.Store;
|
using HermesSocketServer.Store;
|
||||||
|
|
||||||
namespace HermesSocketServer.Services
|
namespace HermesSocketServer.Services
|
||||||
@ -5,12 +7,12 @@ namespace HermesSocketServer.Services
|
|||||||
public class DatabaseService : BackgroundService
|
public class DatabaseService : BackgroundService
|
||||||
{
|
{
|
||||||
private readonly ChannelManager _channels;
|
private readonly ChannelManager _channels;
|
||||||
private readonly VoiceStore _voices;
|
private readonly IStore<string, TTSVoice> _voices;
|
||||||
private readonly UserStore _users;
|
private readonly IStore<string, User> _users;
|
||||||
private readonly ServerConfiguration _configuration;
|
private readonly ServerConfiguration _configuration;
|
||||||
private readonly Serilog.ILogger _logger;
|
private readonly Serilog.ILogger _logger;
|
||||||
|
|
||||||
public DatabaseService(ChannelManager channels, VoiceStore voices, UserStore users, ServerConfiguration configuration, Serilog.ILogger logger)
|
public DatabaseService(ChannelManager channels, IStore<string, TTSVoice> voices, IStore<string, User> users, ServerConfiguration configuration, Serilog.ILogger logger)
|
||||||
{
|
{
|
||||||
_channels = channels;
|
_channels = channels;
|
||||||
_voices = voices;
|
_voices = voices;
|
||||||
@ -21,10 +23,10 @@ namespace HermesSocketServer.Services
|
|||||||
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
|
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
_logger.Information("Loading TTS voices...");
|
|
||||||
await _voices.Load();
|
|
||||||
_logger.Information("Loading users...");
|
_logger.Information("Loading users...");
|
||||||
await _users.Load();
|
await _users.Load();
|
||||||
|
_logger.Information("Loading TTS voices...");
|
||||||
|
await _voices.Load();
|
||||||
|
|
||||||
await Task.Run(async () =>
|
await Task.Run(async () =>
|
||||||
{
|
{
|
||||||
@ -32,12 +34,11 @@ namespace HermesSocketServer.Services
|
|||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
await Task.WhenAll([
|
await _users.Save();
|
||||||
_voices.Save(),
|
await _voices.Save();
|
||||||
_users.Save(),
|
await _channels.Save();
|
||||||
_channels.Save(),
|
|
||||||
Task.Delay(TimeSpan.FromSeconds(_configuration.Database.SaveDelayInSeconds)),
|
await Task.Delay(TimeSpan.FromSeconds(_configuration.Database.SaveDelayInSeconds));
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -6,23 +6,25 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
{
|
{
|
||||||
public class ChatterHandler : ISocketHandler
|
public class ChatterHandler : ISocketHandler
|
||||||
{
|
{
|
||||||
|
private const int CHATTER_BUFFER_SIZE = 2000;
|
||||||
|
|
||||||
public int OperationCode { get; } = 6;
|
public int OperationCode { get; } = 6;
|
||||||
private readonly Database _database;
|
private readonly Database _database;
|
||||||
private readonly HashSet<long> _chatters;
|
private readonly HashSet<long> _chatters;
|
||||||
private readonly ChatterMessage[] _array;
|
private readonly long[] _array;
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
private readonly object _lock;
|
private readonly Mutex _lock;
|
||||||
private int _index;
|
private int _index;
|
||||||
|
|
||||||
public ChatterHandler(Database database, ILogger logger)
|
public ChatterHandler(Database database, ILogger logger)
|
||||||
{
|
{
|
||||||
_database = database;
|
_database = database;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_chatters = new HashSet<long>(1001);
|
_chatters = new HashSet<long>(CHATTER_BUFFER_SIZE);
|
||||||
_array = new ChatterMessage[1000];
|
_array = new long[CHATTER_BUFFER_SIZE];
|
||||||
_index = -1;
|
_index = -1;
|
||||||
_lock = new object();
|
_lock = new Mutex();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Execute<T>(WebSocketUser sender, T message, HermesSocketManager sockets)
|
public async Task Execute<T>(WebSocketUser sender, T message, HermesSocketManager sockets)
|
||||||
@ -30,8 +32,9 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
if (message is not ChatterMessage data || sender.Id == null)
|
if (message is not ChatterMessage data || sender.Id == null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
lock (_lock)
|
try
|
||||||
{
|
{
|
||||||
|
_lock.WaitOne();
|
||||||
if (_chatters.Contains(data.Id))
|
if (_chatters.Contains(data.Id))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
@ -40,7 +43,16 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
if (_index == _array.Length - 1)
|
if (_index == _array.Length - 1)
|
||||||
_index = -1;
|
_index = -1;
|
||||||
|
|
||||||
_array[++_index] = data;
|
var previous = _array[++_index];
|
||||||
|
if (previous != 0)
|
||||||
|
{
|
||||||
|
_chatters.Remove(previous);
|
||||||
|
}
|
||||||
|
_array[_index] = data.Id;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_lock.ReleaseMutex();
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
|
@ -7,18 +7,25 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
{
|
{
|
||||||
public class EmoteDetailsHandler : ISocketHandler
|
public class EmoteDetailsHandler : ISocketHandler
|
||||||
{
|
{
|
||||||
|
private const int EMOTE_BUFFER_SIZE = 5000;
|
||||||
|
|
||||||
public int OperationCode { get; } = 7;
|
public int OperationCode { get; } = 7;
|
||||||
private readonly Database _database;
|
private readonly Database _database;
|
||||||
private readonly HashSet<string> _emotes;
|
private readonly HashSet<string> _emotes;
|
||||||
|
private readonly string[] _array;
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
private readonly object _lock;
|
private readonly Mutex _mutex;
|
||||||
|
|
||||||
|
private int _index;
|
||||||
|
|
||||||
public EmoteDetailsHandler(Database database, ILogger logger)
|
public EmoteDetailsHandler(Database database, ILogger logger)
|
||||||
{
|
{
|
||||||
_database = database;
|
_database = database;
|
||||||
|
_emotes = new HashSet<string>(EMOTE_BUFFER_SIZE);
|
||||||
|
_array = new string[EMOTE_BUFFER_SIZE];
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_emotes = new HashSet<string>(501);
|
_mutex = new Mutex();
|
||||||
_lock = new object();
|
_index = -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Execute<T>(WebSocketUser sender, T message, HermesSocketManager sockets)
|
public async Task Execute<T>(WebSocketUser sender, T message, HermesSocketManager sockets)
|
||||||
@ -26,28 +33,43 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
if (message is not EmoteDetailsMessage data || sender.Id == null)
|
if (message is not EmoteDetailsMessage data || sender.Id == null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
if (data.Emotes == null)
|
if (data.Emotes == null || !data.Emotes.Any())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
if (!data.Emotes.Any())
|
try
|
||||||
return;
|
|
||||||
|
|
||||||
lock (_lock)
|
|
||||||
{
|
{
|
||||||
|
_mutex.WaitOne();
|
||||||
foreach (var entry in data.Emotes)
|
foreach (var entry in data.Emotes)
|
||||||
{
|
{
|
||||||
if (_emotes.Contains(entry.Key))
|
if (_emotes.Contains(entry.Key))
|
||||||
{
|
{
|
||||||
_emotes.Remove(entry.Key);
|
data.Emotes.Remove(entry.Key);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
_emotes.Add(entry.Key);
|
_emotes.Add(entry.Key);
|
||||||
|
|
||||||
|
if (_index == _array.Length - 1)
|
||||||
|
_index = -1;
|
||||||
|
|
||||||
|
var previous = _array[++_index];
|
||||||
|
if (previous != null)
|
||||||
|
{
|
||||||
|
_emotes.Remove(previous);
|
||||||
}
|
}
|
||||||
|
_array[_index] = entry.Key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_mutex.ReleaseMutex();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!data.Emotes.Any())
|
||||||
|
return;
|
||||||
|
|
||||||
int rows = 0;
|
int rows = 0;
|
||||||
string sql = "INSERT INTO \"Emote\" (id, name) VALUES (@idd, @name)";
|
string sql = "INSERT INTO \"Emote\" (id, name) VALUES (@idd, @name) ON CONFLICT (id) DO UPDATE SET name = @name;";
|
||||||
using (var connection = await _database.DataSource.OpenConnectionAsync())
|
using (var connection = await _database.DataSource.OpenConnectionAsync())
|
||||||
{
|
{
|
||||||
using (var command = new NpgsqlCommand(sql, connection))
|
using (var command = new NpgsqlCommand(sql, connection))
|
||||||
@ -70,8 +92,6 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -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 Mutex _mutex;
|
||||||
|
|
||||||
private int _index;
|
private int _index;
|
||||||
|
|
||||||
@ -20,8 +21,9 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
{
|
{
|
||||||
_database = database;
|
_database = database;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_history = new HashSet<string>(101);
|
_history = new HashSet<string>(1001);
|
||||||
_array = new EmoteUsageMessage[100];
|
_array = new EmoteUsageMessage[1000];
|
||||||
|
_mutex = new Mutex();
|
||||||
_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)
|
try
|
||||||
{
|
{
|
||||||
if (_history.Contains(data.MessageId))
|
if (_history.Contains(data.MessageId))
|
||||||
{
|
{
|
||||||
@ -48,6 +50,10 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
|
|
||||||
_array[_index] = data;
|
_array[_index] = data;
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_mutex.ReleaseMutex();
|
||||||
|
}
|
||||||
|
|
||||||
int rows = 0;
|
int rows = 0;
|
||||||
string sql = "INSERT INTO \"EmoteUsageHistory\" (timestamp, \"broadcasterId\", \"emoteId\", \"chatterId\") VALUES (@time, @broadcaster, @emote, @chatter)";
|
string sql = "INSERT INTO \"EmoteUsageHistory\" (timestamp, \"broadcasterId\", \"emoteId\", \"chatterId\") VALUES (@time, @broadcaster, @emote, @chatter)";
|
||||||
|
@ -12,14 +12,14 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
public int OperationCode { get; } = 1;
|
public int OperationCode { get; } = 1;
|
||||||
|
|
||||||
private readonly ChannelManager _manager;
|
private readonly ChannelManager _manager;
|
||||||
private readonly VoiceStore _voices;
|
private readonly IStore<string, TTSVoice> _voices;
|
||||||
private readonly ServerConfiguration _configuration;
|
private readonly ServerConfiguration _configuration;
|
||||||
private readonly Database _database;
|
private readonly Database _database;
|
||||||
private readonly HermesSocketManager _sockets;
|
private readonly HermesSocketManager _sockets;
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
private readonly object _lock;
|
private readonly SemaphoreSlim _semaphore;
|
||||||
|
|
||||||
public HermesLoginHandler(ChannelManager manager, VoiceStore voices, ServerConfiguration configuration, Database database, HermesSocketManager sockets, ILogger logger)
|
public HermesLoginHandler(ChannelManager manager, IStore<string, TTSVoice> voices, ServerConfiguration configuration, Database database, HermesSocketManager sockets, ILogger logger)
|
||||||
{
|
{
|
||||||
_manager = manager;
|
_manager = manager;
|
||||||
_voices = voices;
|
_voices = voices;
|
||||||
@ -27,7 +27,7 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
_database = database;
|
_database = database;
|
||||||
_sockets = sockets;
|
_sockets = sockets;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_lock = new object();
|
_semaphore = new SemaphoreSlim(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -42,25 +42,30 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
var result = await _database.ExecuteScalar(sql, new Dictionary<string, object>() { { "key", data.ApiKey } });
|
var result = await _database.ExecuteScalar(sql, new Dictionary<string, object>() { { "key", data.ApiKey } });
|
||||||
string? userId = result?.ToString();
|
string? userId = result?.ToString();
|
||||||
|
|
||||||
if (userId == null)
|
if (string.IsNullOrWhiteSpace(userId))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
lock (_lock)
|
IEnumerable<WebSocketUser?> recipients = Enumerable.Empty<WebSocketUser?>();
|
||||||
|
try
|
||||||
{
|
{
|
||||||
|
await _semaphore.WaitAsync();
|
||||||
if (sender.Id != null)
|
if (sender.Id != null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
sender.Id = userId;
|
sender.Id = userId;
|
||||||
|
sender.Slave = data.WebLogin || recipients.Where(r => r != null && !r.WebLogin).Any();
|
||||||
|
recipients = _sockets.GetSockets(userId).ToList().Where(s => s.SessionId != sender.SessionId);
|
||||||
|
|
||||||
sender.ApiKey = data.ApiKey;
|
sender.ApiKey = data.ApiKey;
|
||||||
sender.WebLogin = data.WebLogin;
|
sender.WebLogin = data.WebLogin;
|
||||||
}
|
|
||||||
|
|
||||||
|
// Fetch channel data.
|
||||||
var channel = _manager.Get(userId);
|
var channel = _manager.Get(userId);
|
||||||
if (channel == null)
|
if (channel == null)
|
||||||
{
|
{
|
||||||
channel = await _manager.Add(userId);
|
channel = await _manager.Add(userId);
|
||||||
if (channel == null)
|
if (channel == null)
|
||||||
return;
|
throw new Exception("Channel does not exist.");
|
||||||
}
|
}
|
||||||
|
|
||||||
sender.Name = channel.User.Name;
|
sender.Name = channel.User.Name;
|
||||||
@ -71,56 +76,38 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
_logger.Error($"Could not find username for a certain user [user id: {userId}][api key: {data.ApiKey}]");
|
_logger.Error($"Could not find username for a certain user [user id: {userId}][api key: {data.ApiKey}]");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
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)
|
||||||
|
{
|
||||||
|
_logger.Warning($"Could not find the Provider Account Id [user id: {userId}][provider: twitch]");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var voices = _voices.Get();
|
||||||
var ack = new LoginAckMessage()
|
var ack = new LoginAckMessage()
|
||||||
{
|
{
|
||||||
UserId = userId,
|
UserId = userId,
|
||||||
|
ProviderAccountId = providerId,
|
||||||
|
SessionId = sender.SessionId,
|
||||||
|
UserName = channel.User.Name,
|
||||||
OwnerId = _configuration.Tts.OwnerId,
|
OwnerId = _configuration.Tts.OwnerId,
|
||||||
Admin = sender.Admin,
|
Admin = sender.Admin,
|
||||||
WebLogin = data.WebLogin,
|
WebLogin = data.WebLogin,
|
||||||
|
WordFilters = channel.Filters.Get().Values,
|
||||||
|
DefaultTTSVoice = channel.User.DefaultVoice ?? _configuration.Tts.DefaultTtsVoice,
|
||||||
|
TTSVoicesAvailable = _voices.Get().ToDictionary(v => v.Key, v => v.Value.Name),
|
||||||
|
EnabledTTSVoices = channel.VoiceStates.Get().Values.Where(v => v.Enabled && voices.ContainsKey(v.Id)).Select(v => voices[v.Id].Name).ToList(),
|
||||||
|
Connections = channel.Connections.Get().Values.ToList(),
|
||||||
|
Slave = sender.Slave,
|
||||||
};
|
};
|
||||||
|
|
||||||
var userIdDict = new Dictionary<string, object>() { { "user", userId } };
|
|
||||||
ack.Connections = new List<Connection>();
|
|
||||||
string sql3 = "select \"name\", \"type\", \"clientId\", \"accessToken\", \"grantType\", \"scope\", \"expiresAt\", \"default\" from \"Connection\" where \"userId\" = @user";
|
|
||||||
await _database.Execute(sql3, userIdDict, sql =>
|
|
||||||
ack.Connections.Add(new Connection()
|
|
||||||
{
|
|
||||||
Name = sql.GetString(0),
|
|
||||||
Type = sql.GetString(1),
|
|
||||||
ClientId = sql.GetString(2),
|
|
||||||
AccessToken = sql.GetString(3),
|
|
||||||
GrantType = sql.GetString(4),
|
|
||||||
Scope = sql.GetString(5),
|
|
||||||
ExpiresAt = sql.GetDateTime(6),
|
|
||||||
Default = sql.GetBoolean(7)
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
ack.TTSVoicesAvailable = _voices.Get().ToDictionary(v => v.Key, v => v.Value.Name);
|
|
||||||
|
|
||||||
ack.EnabledTTSVoices = new List<string>();
|
|
||||||
string sql5 = $"SELECT v.name FROM \"TtsVoiceState\" s "
|
|
||||||
+ "INNER JOIN \"TtsVoice\" v ON s.\"ttsVoiceId\" = v.id "
|
|
||||||
+ "WHERE \"userId\" = @user AND state = true";
|
|
||||||
await _database.Execute(sql5, userIdDict, (r) => ack.EnabledTTSVoices.Add(r.GetString(0)));
|
|
||||||
|
|
||||||
ack.WordFilters = new List<TTSWordFilter>();
|
|
||||||
string sql6 = $"SELECT id, search, replace FROM \"TtsWordFilter\" WHERE \"userId\" = @user";
|
|
||||||
await _database.Execute(sql6, userIdDict, (r) => ack.WordFilters.Add(new TTSWordFilter()
|
|
||||||
{
|
|
||||||
Id = r.GetString(0),
|
|
||||||
Search = r.GetString(1),
|
|
||||||
Replace = r.GetString(2)
|
|
||||||
}));
|
|
||||||
|
|
||||||
ack.DefaultTTSVoice = channel.User.DefaultVoice ?? _configuration.Tts.DefaultTtsVoice;
|
|
||||||
|
|
||||||
await sender.Send(2, ack);
|
await sender.Send(2, ack);
|
||||||
|
|
||||||
string version = data.MajorVersion == null ? "unknown" : $"{data.MajorVersion}.{data.MinorVersion}";
|
// Sending notification to other clients about another client logging in.
|
||||||
|
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}]");
|
_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()
|
ack = new LoginAckMessage()
|
||||||
@ -131,13 +118,12 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
WebLogin = data.WebLogin
|
WebLogin = data.WebLogin
|
||||||
};
|
};
|
||||||
|
|
||||||
var recipients = _sockets.GetSockets(userId).ToList().Where(s => s.UID != sender.UID);
|
|
||||||
var tasks = new List<Task>();
|
var tasks = new List<Task>();
|
||||||
foreach (var socket in recipients)
|
foreach (var socket in recipients)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
tasks.Add(socket.Send(2, ack));
|
tasks.Add(socket!.Send(2, ack));
|
||||||
}
|
}
|
||||||
catch (Exception)
|
catch (Exception)
|
||||||
{
|
{
|
||||||
@ -145,5 +131,10 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
}
|
}
|
||||||
await Task.WhenAll(tasks);
|
await Task.WhenAll(tasks);
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_semaphore.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -15,10 +15,10 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public async Task Execute<T>(WebSocketUser sender, T data, HermesSocketManager sockets)
|
public Task Execute<T>(WebSocketUser sender, T data, HermesSocketManager sockets)
|
||||||
{
|
{
|
||||||
if (data is not LoggingMessage message || sender.Id == null)
|
if (data is not LoggingMessage message || sender.Id == null)
|
||||||
return;
|
return Task.CompletedTask;
|
||||||
|
|
||||||
Action<Exception?, string> logging;
|
Action<Exception?, string> logging;
|
||||||
if (message.Level == HermesLoggingLevel.Trace)
|
if (message.Level == HermesLoggingLevel.Trace)
|
||||||
@ -35,10 +35,11 @@ namespace HermesSocketServer.Socket.Handlers
|
|||||||
logging = _logger.Fatal;
|
logging = _logger.Fatal;
|
||||||
else {
|
else {
|
||||||
_logger.Warning("Failed to receive a logging level from client.");
|
_logger.Warning("Failed to receive a logging level from client.");
|
||||||
return;
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -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;
|
||||||
|
@ -6,9 +6,10 @@ namespace HermesSocketServer.Socket
|
|||||||
{
|
{
|
||||||
public class HermesSocketManager
|
public class HermesSocketManager
|
||||||
{
|
{
|
||||||
private IList<WebSocketUser> _sockets;
|
private readonly IList<WebSocketUser> _sockets;
|
||||||
private System.Timers.Timer _timer;
|
private readonly System.Timers.Timer _timer;
|
||||||
private ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
|
private readonly object _lock = new object();
|
||||||
|
|
||||||
|
|
||||||
public HermesSocketManager(ILogger logger)
|
public HermesSocketManager(ILogger logger)
|
||||||
@ -18,32 +19,41 @@ namespace HermesSocketServer.Socket
|
|||||||
_timer.Elapsed += async (sender, e) => await HandleHeartbeats(e);
|
_timer.Elapsed += async (sender, e) => await HandleHeartbeats(e);
|
||||||
_timer.Enabled = true;
|
_timer.Enabled = true;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
_lock = new object();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public void Add(WebSocketUser socket)
|
public void Add(WebSocketUser socket)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
{
|
{
|
||||||
_sockets.Add(socket);
|
_sockets.Add(socket);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public IList<WebSocketUser> GetAllSockets()
|
public IList<WebSocketUser> GetAllSockets()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
{
|
{
|
||||||
return _sockets.AsReadOnly();
|
return _sockets.AsReadOnly();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public IEnumerable<WebSocketUser> GetSockets(string userId)
|
public IEnumerable<WebSocketUser> GetSockets(string userId)
|
||||||
{
|
{
|
||||||
foreach (var socket in _sockets)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
if (socket.Id == userId)
|
return _sockets.Where(s => s.Id == userId);
|
||||||
yield return socket;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool Remove(WebSocketUser socket)
|
public bool Remove(WebSocketUser socket)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
{
|
{
|
||||||
return _sockets.Remove(socket);
|
return _sockets.Remove(socket);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async Task HandleHeartbeats(ElapsedEventArgs e)
|
private async Task HandleHeartbeats(ElapsedEventArgs e)
|
||||||
{
|
{
|
||||||
|
@ -22,8 +22,9 @@ namespace HermesSocketServer.Socket
|
|||||||
public WebSocketState State { get => _socket.State; }
|
public WebSocketState State { get => _socket.State; }
|
||||||
public IPAddress? IPAddress { get => _ipAddress; }
|
public IPAddress? IPAddress { get => _ipAddress; }
|
||||||
public bool Connected { get => _connected; }
|
public bool Connected { get => _connected; }
|
||||||
public string UID { get; }
|
public bool Slave { get; set; }
|
||||||
public string ApiKey { get; set; }
|
public string SessionId { get; }
|
||||||
|
public string? ApiKey { get; set; }
|
||||||
public string? Id { get; set; }
|
public string? Id { get; set; }
|
||||||
public string? Name { get; set; }
|
public string? Name { get; set; }
|
||||||
public bool Admin { get; set; }
|
public bool Admin { get; set; }
|
||||||
@ -43,7 +44,7 @@ namespace HermesSocketServer.Socket
|
|||||||
Admin = false;
|
Admin = false;
|
||||||
WebLogin = false;
|
WebLogin = false;
|
||||||
_cts = new CancellationTokenSource();
|
_cts = new CancellationTokenSource();
|
||||||
UID = Guid.NewGuid().ToString("D");
|
SessionId = Guid.NewGuid().ToString("D");
|
||||||
LastHeartbeatReceived = DateTime.UtcNow;
|
LastHeartbeatReceived = DateTime.UtcNow;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
61
Startup.cs
61
Startup.cs
@ -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;
|
||||||
@ -16,6 +15,10 @@ using Microsoft.AspNetCore.Connections;
|
|||||||
using HermesSocketServer.Validators;
|
using HermesSocketServer.Validators;
|
||||||
using HermesSocketServer.Store;
|
using HermesSocketServer.Store;
|
||||||
using HermesSocketServer.Services;
|
using HermesSocketServer.Services;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Models;
|
||||||
|
|
||||||
|
|
||||||
var yamlDeserializer = new DeserializerBuilder()
|
var yamlDeserializer = new DeserializerBuilder()
|
||||||
@ -79,29 +82,63 @@ s.AddSingleton<ISocketHandler, EmoteUsageHandler>();
|
|||||||
s.AddSingleton<VoiceIdValidator>();
|
s.AddSingleton<VoiceIdValidator>();
|
||||||
s.AddSingleton<VoiceNameValidator>();
|
s.AddSingleton<VoiceNameValidator>();
|
||||||
|
|
||||||
|
// Database Tables
|
||||||
|
if (configuration.Database.Tables != null)
|
||||||
|
{
|
||||||
|
foreach (var table in configuration.Database.Tables)
|
||||||
|
s.AddKeyedTransient<DatabaseTable>(table.Key, (sp, _) => table.Value);
|
||||||
|
}
|
||||||
|
|
||||||
// Stores
|
// Stores
|
||||||
s.AddSingleton<VoiceStore>();
|
s.AddSingleton<IStore<string, TTSVoice>, VoiceStore>();
|
||||||
s.AddSingleton<UserStore>();
|
s.AddSingleton<IStore<string, User>, UserStore>();
|
||||||
|
|
||||||
// Request handlers
|
// Request handlers
|
||||||
s.AddSingleton<IRequest, GetTTSUsers>();
|
s.AddSingleton<IRequest, CreateConnection>();
|
||||||
s.AddSingleton<IRequest, GetTTSVoices>();
|
s.AddSingleton<IRequest, CreateGroup>();
|
||||||
s.AddSingleton<IRequest, GetTTSWordFilters>();
|
s.AddSingleton<IRequest, CreateGroupChatter>();
|
||||||
|
s.AddSingleton<IRequest, CreateGroupPermission>();
|
||||||
|
s.AddSingleton<IRequest, CreatePolicy>();
|
||||||
|
s.AddSingleton<IRequest, CreateRedeemableAction>();
|
||||||
|
s.AddSingleton<IRequest, CreateRedemption>();
|
||||||
|
s.AddSingleton<IRequest, CreateTTSFilter>();
|
||||||
s.AddSingleton<IRequest, CreateTTSUser>();
|
s.AddSingleton<IRequest, CreateTTSUser>();
|
||||||
s.AddSingleton<IRequest, CreateTTSVoice>();
|
s.AddSingleton<IRequest, CreateTTSVoice>();
|
||||||
|
s.AddSingleton<IRequest, DeleteConnection>();
|
||||||
|
s.AddSingleton<IRequest, DeleteGroup>();
|
||||||
|
s.AddSingleton<IRequest, DeleteGroupChatter>();
|
||||||
|
s.AddSingleton<IRequest, DeleteGroupPermission>();
|
||||||
|
s.AddSingleton<IRequest, DeletePolicy>();
|
||||||
|
s.AddSingleton<IRequest, DeleteRedeemableAction>();
|
||||||
|
s.AddSingleton<IRequest, DeleteRedemption>();
|
||||||
|
s.AddSingleton<IRequest, DeleteTTSFilter>();
|
||||||
s.AddSingleton<IRequest, DeleteTTSVoice>();
|
s.AddSingleton<IRequest, DeleteTTSVoice>();
|
||||||
s.AddSingleton<IRequest, UpdateTTSUser>();
|
|
||||||
s.AddSingleton<IRequest, UpdateTTSVoice>();
|
|
||||||
s.AddSingleton<IRequest, GetChatterIds>();
|
s.AddSingleton<IRequest, GetChatterIds>();
|
||||||
s.AddSingleton<IRequest, GetConnections>();
|
s.AddSingleton<IRequest, GetConnections>();
|
||||||
s.AddSingleton<IRequest, GetDefaultTTSVoice>();
|
s.AddSingleton<IRequest, GetDefaultTTSVoice>();
|
||||||
s.AddSingleton<IRequest, GetEmotes>();
|
s.AddSingleton<IRequest, GetEmotes>();
|
||||||
s.AddSingleton<IRequest, GetEnabledTTSVoices>();
|
s.AddSingleton<IRequest, GetEnabledTTSVoices>();
|
||||||
|
s.AddSingleton<IRequest, GetGroups>();
|
||||||
|
s.AddSingleton<IRequest, GetGroupPermissions>();
|
||||||
s.AddSingleton<IRequest, GetPermissions>();
|
s.AddSingleton<IRequest, GetPermissions>();
|
||||||
s.AddSingleton<IRequest, GetRedemptions>();
|
|
||||||
s.AddSingleton<IRequest, GetRedeemableActions>();
|
s.AddSingleton<IRequest, GetRedeemableActions>();
|
||||||
s.AddSingleton<IRequest, UpdateTTSVoiceState>();
|
s.AddSingleton<IRequest, GetRedemptions>();
|
||||||
|
s.AddSingleton<IRequest, GetPolicies>();
|
||||||
|
s.AddSingleton<IRequest, GetTTSUsers>();
|
||||||
|
s.AddSingleton<IRequest, GetTTSVoices>();
|
||||||
|
s.AddSingleton<IRequest, GetTTSWordFilters>();
|
||||||
|
s.AddSingleton<IRequest, UpdateConnection>();
|
||||||
s.AddSingleton<IRequest, UpdateDefaultTTSVoice>();
|
s.AddSingleton<IRequest, UpdateDefaultTTSVoice>();
|
||||||
|
s.AddSingleton<IRequest, UpdateGroup>();
|
||||||
|
s.AddSingleton<IRequest, UpdateGroupChatter>();
|
||||||
|
s.AddSingleton<IRequest, UpdateGroupPermission>();
|
||||||
|
s.AddSingleton<IRequest, UpdatePolicy>();
|
||||||
|
s.AddSingleton<IRequest, UpdateRedeemableAction>();
|
||||||
|
s.AddSingleton<IRequest, UpdateRedemption>();
|
||||||
|
s.AddSingleton<IRequest, UpdateTTSFilter>();
|
||||||
|
s.AddSingleton<IRequest, UpdateTTSUser>();
|
||||||
|
s.AddSingleton<IRequest, UpdateTTSVoice>();
|
||||||
|
s.AddSingleton<IRequest, UpdateTTSVoiceState>();
|
||||||
|
|
||||||
// Managers
|
// Managers
|
||||||
s.AddSingleton<ChannelManager>();
|
s.AddSingleton<ChannelManager>();
|
||||||
@ -126,9 +163,7 @@ var wsOptions = new WebSocketOptions()
|
|||||||
{
|
{
|
||||||
KeepAliveInterval = TimeSpan.FromSeconds(30)
|
KeepAliveInterval = TimeSpan.FromSeconds(30)
|
||||||
};
|
};
|
||||||
// wsOptions.AllowedOrigins.Add("wss://tomtospeech.com");
|
|
||||||
//wsOptions.AllowedOrigins.Add("ws.tomtospeech.com");
|
|
||||||
//wsOptions.AllowedOrigins.Add("hermes-ws.goblincaves.com");
|
|
||||||
app.UseWebSockets(wsOptions);
|
app.UseWebSockets(wsOptions);
|
||||||
|
|
||||||
var options = app.Services.GetRequiredService<JsonSerializerOptions>();
|
var options = app.Services.GetRequiredService<JsonSerializerOptions>();
|
||||||
|
66
Store/ActionStore.cs
Normal file
66
Store/ActionStore.cs
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Store
|
||||||
|
{
|
||||||
|
public class ActionStore : ComplexAutoSavedStore<string, RedeemableAction>
|
||||||
|
{
|
||||||
|
private readonly string _userId;
|
||||||
|
private readonly Database _database;
|
||||||
|
private readonly Serilog.ILogger _logger;
|
||||||
|
|
||||||
|
|
||||||
|
public ActionStore(string userId, DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
|
{
|
||||||
|
_userId = userId;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Load()
|
||||||
|
{
|
||||||
|
var data = new Dictionary<string, object>() { { "user", _userId } };
|
||||||
|
string sql = $"SELECT name, type, has_message, data FROM \"Action\" WHERE \"userId\" = @user";
|
||||||
|
await _database.Execute(sql, data, (reader) =>
|
||||||
|
{
|
||||||
|
var name = reader.GetString(0);
|
||||||
|
_store.Add(name, new RedeemableAction()
|
||||||
|
{
|
||||||
|
UserId = _userId,
|
||||||
|
Name = name,
|
||||||
|
Type = reader.GetString(1),
|
||||||
|
HasMessage = reader.GetBoolean(2),
|
||||||
|
Data = JsonSerializer.Deserialize<IDictionary<string, string>>(reader.GetString(3))!
|
||||||
|
});
|
||||||
|
});
|
||||||
|
_logger.Information($"Loaded {_store.Count} redeemable actions from database.");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialAdd(string key, RedeemableAction value)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||||
|
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.UserId, nameof(value.UserId));
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue, nameof(newValue));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.UserId, nameof(newValue.UserId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.Name, nameof(newValue.Name));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.Type, nameof(newValue.Type));
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue.Data, nameof(newValue.Data));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.UserId, newValue.UserId, nameof(oldValue.UserId));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.Name, newValue.Name, nameof(oldValue.Name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
71
Store/ChatterGroupStore.cs
Normal file
71
Store/ChatterGroupStore.cs
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Store
|
||||||
|
{
|
||||||
|
public class ChatterGroupStore : ComplexAutoSavedStore<string, GroupChatter>
|
||||||
|
{
|
||||||
|
private readonly string _userId;
|
||||||
|
private readonly string _groupId;
|
||||||
|
private readonly Database _database;
|
||||||
|
private readonly Serilog.ILogger _logger;
|
||||||
|
|
||||||
|
public string GroupId { get => _groupId; }
|
||||||
|
|
||||||
|
|
||||||
|
public ChatterGroupStore(string userId, string groupId, DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
|
{
|
||||||
|
_userId = userId;
|
||||||
|
_groupId = groupId;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Load()
|
||||||
|
{
|
||||||
|
var data = new Dictionary<string, object>() { { "user", _userId }, { "group", new Guid(_groupId) } };
|
||||||
|
string sql = $"SELECT \"chatterId\", \"chatterLabel\" FROM \"ChatterGroup\" WHERE \"userId\" = @user AND \"groupId\" = @group";
|
||||||
|
await _database.Execute(sql, data, (reader) =>
|
||||||
|
{
|
||||||
|
var chatterId = reader.GetInt32(0).ToString();
|
||||||
|
_rwls.EnterWriteLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_store.Add(chatterId, new GroupChatter()
|
||||||
|
{
|
||||||
|
UserId = _userId,
|
||||||
|
GroupId = _groupId,
|
||||||
|
ChatterId = reader.GetInt32(0),
|
||||||
|
ChatterLabel = reader.GetString(1),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitWriteLock();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
_logger.Information($"Loaded {_store.Count} group chatters from database [group id: {_groupId}]");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialAdd(string key, GroupChatter value)
|
||||||
|
{
|
||||||
|
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.ChatterId, nameof(value.ChatterId));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialModify(string key, GroupChatter oldValue, GroupChatter newValue)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue, nameof(newValue));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.GroupId, nameof(newValue.GroupId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.GroupId, nameof(newValue.GroupId));
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue.ChatterId, nameof(newValue.ChatterId));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.UserId, newValue.UserId, nameof(oldValue.UserId));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.GroupId, newValue.GroupId, nameof(oldValue.GroupId));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,29 +1,22 @@
|
|||||||
using HermesSocketLibrary.db;
|
using HermesSocketLibrary.db;
|
||||||
using HermesSocketServer.Models;
|
using HermesSocketServer.Models;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
namespace HermesSocketServer.Store
|
namespace HermesSocketServer.Store
|
||||||
{
|
{
|
||||||
public class ChatterStore : GroupSaveStore<string, ChatterVoice>
|
public class ChatterStore : ComplexAutoSavedStore<string, ChatterVoice>
|
||||||
{
|
{
|
||||||
private readonly string _userId;
|
private readonly string _userId;
|
||||||
private readonly Database _database;
|
private readonly Database _database;
|
||||||
private readonly Serilog.ILogger _logger;
|
private readonly Serilog.ILogger _logger;
|
||||||
private readonly GroupSaveSqlGenerator<ChatterVoice> _generator;
|
|
||||||
|
|
||||||
|
|
||||||
public ChatterStore(string userId, Database database, Serilog.ILogger logger) : base(logger)
|
public ChatterStore(string userId, DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
{
|
{
|
||||||
_userId = userId;
|
_userId = userId;
|
||||||
_database = database;
|
_database = database;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
|
||||||
var ctp = new Dictionary<string, string>
|
|
||||||
{
|
|
||||||
{ "chatterId", "ChatterId" },
|
|
||||||
{ "ttsVoiceId", "VoiceId" },
|
|
||||||
{ "userId", "UserId" },
|
|
||||||
};
|
|
||||||
_generator = new GroupSaveSqlGenerator<ChatterVoice>(ctp);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task Load()
|
public override async Task Load()
|
||||||
@ -32,8 +25,8 @@ namespace HermesSocketServer.Store
|
|||||||
string sql = $"SELECT \"chatterId\", \"ttsVoiceId\" FROM \"TtsChatVoice\" WHERE \"userId\" = @user";
|
string sql = $"SELECT \"chatterId\", \"ttsVoiceId\" FROM \"TtsChatVoice\" WHERE \"userId\" = @user";
|
||||||
await _database.Execute(sql, data, (reader) =>
|
await _database.Execute(sql, data, (reader) =>
|
||||||
{
|
{
|
||||||
string chatterId = reader.GetInt64(0).ToString();
|
var chatterId = reader.GetInt64(0);
|
||||||
_store.Add(chatterId, new ChatterVoice()
|
_store.Add(chatterId.ToString(), new ChatterVoice()
|
||||||
{
|
{
|
||||||
UserId = _userId,
|
UserId = _userId,
|
||||||
ChatterId = chatterId,
|
ChatterId = chatterId,
|
||||||
@ -45,56 +38,21 @@ namespace HermesSocketServer.Store
|
|||||||
|
|
||||||
protected override void OnInitialAdd(string key, ChatterVoice value)
|
protected override void OnInitialAdd(string key, ChatterVoice value)
|
||||||
{
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||||
|
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.UserId, nameof(value.UserId));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value.ChatterId, nameof(value.ChatterId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.VoiceId, nameof(value.VoiceId));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnInitialModify(string key, ChatterVoice value)
|
protected override void OnInitialModify(string key, ChatterVoice oldValue, ChatterVoice newValue)
|
||||||
{
|
{
|
||||||
}
|
ArgumentNullException.ThrowIfNull(newValue, nameof(newValue));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.UserId, nameof(newValue.UserId));
|
||||||
protected override void OnInitialRemove(string key)
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(newValue.ChatterId, nameof(newValue.ChatterId));
|
||||||
{
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.VoiceId, nameof(newValue.VoiceId));
|
||||||
}
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.UserId, newValue.UserId, nameof(oldValue.UserId));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.ChatterId, newValue.ChatterId, nameof(oldValue.ChatterId));
|
||||||
public override async Task<bool> Save()
|
|
||||||
{
|
|
||||||
int count = 0;
|
|
||||||
string sql = string.Empty;
|
|
||||||
|
|
||||||
if (_added.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _added.Count;
|
|
||||||
sql = _generator.GenerateInsertSql("TtsChatVoice", _added.Select(a => _store[a]), ["userId", "chatterId", "ttsVoiceId"]);
|
|
||||||
_added.Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.Debug($"TtsChatVoice - Adding {count} rows to database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
if (_modified.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _modified.Count;
|
|
||||||
sql = _generator.GenerateUpdateSql("TtsChatVoice", _modified.Select(m => _store[m]), ["userId", "chatterId"], ["ttsVoiceId"]);
|
|
||||||
_modified.Clear();
|
|
||||||
}
|
|
||||||
_logger.Debug($"TtsChatVoice - Modifying {count} rows in database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
if (_deleted.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _deleted.Count;
|
|
||||||
sql = _generator.GenerateDeleteSql("TtsChatVoice", _deleted, ["userId", "chatterId"]);
|
|
||||||
_deleted.Clear();
|
|
||||||
}
|
|
||||||
_logger.Debug($"TtsChatVoice - Deleting {count} rows from database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
80
Store/ConnectionStore.cs
Normal file
80
Store/ConnectionStore.cs
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Socket.Data;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Store
|
||||||
|
{
|
||||||
|
public class ConnectionStore : ComplexAutoSavedStore<string, Connection>
|
||||||
|
{
|
||||||
|
private readonly string _userId;
|
||||||
|
private readonly Database _database;
|
||||||
|
private readonly Serilog.ILogger _logger;
|
||||||
|
|
||||||
|
public ConnectionStore(string userId, DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
|
{
|
||||||
|
_userId = userId;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Load()
|
||||||
|
{
|
||||||
|
var data = new Dictionary<string, object>() { { "user", _userId } };
|
||||||
|
string sql = $"SELECT name, \"type\", \"clientId\", \"accessToken\", \"grantType\", \"scope\", \"expiresAt\", \"default\" FROM \"Connection\" WHERE \"userId\" = @user";
|
||||||
|
await _database.Execute(sql, data, (reader) =>
|
||||||
|
{
|
||||||
|
var name = reader.GetString(0);
|
||||||
|
_store.Add(name, new Connection()
|
||||||
|
{
|
||||||
|
Name = name,
|
||||||
|
UserId = _userId,
|
||||||
|
Type = reader.GetString(1),
|
||||||
|
ClientId = reader.GetString(2),
|
||||||
|
AccessToken = reader.GetString(3),
|
||||||
|
GrantType = reader.GetString(4),
|
||||||
|
Scope = reader.GetString(5),
|
||||||
|
ExpiresAt = reader.GetDateTime(6),
|
||||||
|
Default = reader.GetBoolean(7),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
_logger.Information($"Loaded {_store.Count} connections from database.");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialAdd(string key, Connection value)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||||
|
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.UserId, nameof(value.UserId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.Name, nameof(value.Name));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.Type, nameof(value.Type));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.ClientId, nameof(value.ClientId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.AccessToken, nameof(value.AccessToken));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.GrantType, nameof(value.GrantType));
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue, nameof(newValue));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.UserId, nameof(newValue.UserId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.Name, nameof(newValue.Name));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.Type, nameof(newValue.Type));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.ClientId, nameof(newValue.ClientId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.AccessToken, nameof(newValue.AccessToken));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.GrantType, nameof(newValue.GrantType));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.Scope, nameof(newValue.Scope));
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue.ExpiresAt, nameof(newValue.ExpiresAt));
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
74
Store/GroupPermissionStore.cs
Normal file
74
Store/GroupPermissionStore.cs
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
|
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, IStore<string, Group> groups, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
|
{
|
||||||
|
_userId = userId;
|
||||||
|
_groups = groups;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Load()
|
||||||
|
{
|
||||||
|
var data = new Dictionary<string, object>() { { "user", _userId } };
|
||||||
|
string sql = $"SELECT id, \"groupId\", path, allow FROM \"GroupPermission\" WHERE \"userId\" = @user";
|
||||||
|
await _database.Execute(sql, data, async (reader) =>
|
||||||
|
{
|
||||||
|
var id = reader.GetGuid(0).ToString();
|
||||||
|
_store.Add(id, new GroupPermission()
|
||||||
|
{
|
||||||
|
Id = id,
|
||||||
|
UserId = _userId,
|
||||||
|
GroupId = reader.GetGuid(1),
|
||||||
|
Path = reader.GetString(2),
|
||||||
|
Allow = await reader.IsDBNullAsync(3) ? null : reader.GetBoolean(3),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
_logger.Information($"Loaded {_store.Count} group permissions from database.");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialAdd(string key, GroupPermission value)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||||
|
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.UserId, nameof(value.UserId));
|
||||||
|
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));
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,138 +0,0 @@
|
|||||||
using System.Reflection;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace HermesSocketServer.Store
|
|
||||||
{
|
|
||||||
public class GroupSaveSqlGenerator<T>
|
|
||||||
{
|
|
||||||
private readonly IDictionary<string, PropertyInfo?> columnPropertyRelations;
|
|
||||||
|
|
||||||
public GroupSaveSqlGenerator(IDictionary<string, string> columnsToProperties)
|
|
||||||
{
|
|
||||||
columnPropertyRelations = columnsToProperties.ToDictionary(p => p.Key, p => typeof(T).GetProperty(p.Value));
|
|
||||||
|
|
||||||
var nullProperties = columnPropertyRelations.Where(p => p.Value == null)
|
|
||||||
.Select(p => columnsToProperties[p.Key]);
|
|
||||||
if (nullProperties.Any())
|
|
||||||
throw new ArgumentException("Some properties do not exist on the values given: " + string.Join(", ", nullProperties));
|
|
||||||
}
|
|
||||||
|
|
||||||
public string GenerateInsertSql(string table, IEnumerable<T> values, IEnumerable<string> columns)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(table))
|
|
||||||
throw new ArgumentException("Value is either null or whitespace-filled.", nameof(table));
|
|
||||||
if (values == null)
|
|
||||||
throw new ArgumentNullException(nameof(values));
|
|
||||||
if (!values.Any())
|
|
||||||
throw new ArgumentException("Empty list given.", nameof(values));
|
|
||||||
if (columns == null)
|
|
||||||
throw new ArgumentNullException(nameof(columns));
|
|
||||||
if (!columns.Any())
|
|
||||||
throw new ArgumentException("Empty list given.", nameof(columns));
|
|
||||||
|
|
||||||
var ctp = columns.ToDictionary(c => c, c => columnPropertyRelations[c]);
|
|
||||||
var sb = new StringBuilder();
|
|
||||||
sb.Append($"INSERT INTO \"{table}\" (\"{string.Join("\", \"", columns)}\") VALUES ");
|
|
||||||
foreach (var value in values)
|
|
||||||
{
|
|
||||||
sb.Append("(");
|
|
||||||
foreach (var column in columns)
|
|
||||||
{
|
|
||||||
var propValue = columnPropertyRelations[column]!.GetValue(value);
|
|
||||||
var propType = columnPropertyRelations[column]!.PropertyType;
|
|
||||||
WriteValue(sb, propValue, propType);
|
|
||||||
sb.Append(",");
|
|
||||||
}
|
|
||||||
sb.Remove(sb.Length - 1, 1)
|
|
||||||
.Append("),");
|
|
||||||
}
|
|
||||||
sb.Remove(sb.Length - 1, 1)
|
|
||||||
.Append(';');
|
|
||||||
return sb.ToString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public string GenerateUpdateSql(string table, IEnumerable<T> values, IEnumerable<string> keyColumns, IEnumerable<string> updateColumns)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(table))
|
|
||||||
throw new ArgumentException("Value is either null or whitespace-filled.", nameof(table));
|
|
||||||
if (values == null)
|
|
||||||
throw new ArgumentNullException(nameof(values));
|
|
||||||
if (!values.Any())
|
|
||||||
throw new ArgumentException("Empty list given.", nameof(values));
|
|
||||||
if (keyColumns == null)
|
|
||||||
throw new ArgumentNullException(nameof(keyColumns));
|
|
||||||
if (!keyColumns.Any())
|
|
||||||
throw new ArgumentException("Empty list given.", nameof(keyColumns));
|
|
||||||
if (updateColumns == null)
|
|
||||||
throw new ArgumentNullException(nameof(updateColumns));
|
|
||||||
if (!updateColumns.Any())
|
|
||||||
throw new ArgumentException("Empty list given.", nameof(updateColumns));
|
|
||||||
|
|
||||||
var columns = keyColumns.Union(updateColumns);
|
|
||||||
var ctp = columns.ToDictionary(c => c, c => columnPropertyRelations[c]);
|
|
||||||
var sb = new StringBuilder();
|
|
||||||
sb.Append($"UPDATE \"{table}\" as t SET {string.Join(", ", updateColumns.Select(c => "\"" + c + "\" = c.\"" + c + "\""))} FROM (VALUES ");
|
|
||||||
foreach (var value in values)
|
|
||||||
{
|
|
||||||
sb.Append("(");
|
|
||||||
foreach (var column in columns)
|
|
||||||
{
|
|
||||||
var propValue = columnPropertyRelations[column]!.GetValue(value);
|
|
||||||
var propType = columnPropertyRelations[column]!.PropertyType;
|
|
||||||
WriteValue(sb, propValue, propType);
|
|
||||||
sb.Append(",");
|
|
||||||
}
|
|
||||||
sb.Remove(sb.Length - 1, 1)
|
|
||||||
.Append("),");
|
|
||||||
}
|
|
||||||
sb.Remove(sb.Length - 1, 1)
|
|
||||||
.Append($") AS c(\"{string.Join("\", \"", columns)}\") WHERE id = c.id;");
|
|
||||||
|
|
||||||
return sb.ToString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public string GenerateDeleteSql(string table, IEnumerable<string> keys, IEnumerable<string> keyColumns)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(table))
|
|
||||||
throw new ArgumentException("Value is either null or whitespace-filled.", nameof(table));
|
|
||||||
if (keys == null)
|
|
||||||
throw new ArgumentNullException(nameof(keys));
|
|
||||||
if (!keys.Any())
|
|
||||||
throw new ArgumentException("Empty list given.", nameof(keys));
|
|
||||||
if (keyColumns == null)
|
|
||||||
throw new ArgumentNullException(nameof(keyColumns));
|
|
||||||
if (!keyColumns.Any())
|
|
||||||
throw new ArgumentException("Empty list given.", nameof(keyColumns));
|
|
||||||
|
|
||||||
var ctp = keyColumns.ToDictionary(c => c, c => columnPropertyRelations[c]);
|
|
||||||
var sb = new StringBuilder();
|
|
||||||
sb.Append($"DELETE FROM \"{table}\" WHERE (\"{string.Join("\", \"", keyColumns)}\") IN (");
|
|
||||||
foreach (var k in keys)
|
|
||||||
{
|
|
||||||
sb.Append("(");
|
|
||||||
foreach (var column in keyColumns)
|
|
||||||
{
|
|
||||||
var propType = columnPropertyRelations[column]!.PropertyType;
|
|
||||||
WriteValue(sb, k, propType);
|
|
||||||
sb.Append(",");
|
|
||||||
}
|
|
||||||
sb.Remove(sb.Length - 1, 1)
|
|
||||||
.Append("),");
|
|
||||||
}
|
|
||||||
sb.Remove(sb.Length - 1, 1)
|
|
||||||
.Append(");");
|
|
||||||
|
|
||||||
return sb.ToString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void WriteValue(StringBuilder sb, object? value, Type type)
|
|
||||||
{
|
|
||||||
if (type == typeof(string))
|
|
||||||
sb.Append("'")
|
|
||||||
.Append(value)
|
|
||||||
.Append("'");
|
|
||||||
else
|
|
||||||
sb.Append(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
97
Store/GroupStore.cs
Normal file
97
Store/GroupStore.cs
Normal file
@ -0,0 +1,97 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Store
|
||||||
|
{
|
||||||
|
public class GroupStore : AutoSavedStore<string, Group>
|
||||||
|
{
|
||||||
|
public static readonly string[] AUTO_GENERATED_GROUP_NAMES = ["everyone", "subscribers", "vip", "moderators", "broadcaster"];
|
||||||
|
|
||||||
|
private IDictionary<string, ChatterGroupStore> _chatters;
|
||||||
|
private readonly string _userId;
|
||||||
|
private readonly Database _database;
|
||||||
|
private readonly ServerConfiguration _configuration;
|
||||||
|
private readonly Serilog.ILogger _logger;
|
||||||
|
|
||||||
|
public IDictionary<string, ChatterGroupStore> Chatters { get => _chatters; }
|
||||||
|
|
||||||
|
|
||||||
|
public GroupStore(string userId, DatabaseTable table, Database database, ServerConfiguration configuration, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
|
{
|
||||||
|
_userId = userId;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
_configuration = configuration;
|
||||||
|
_chatters = new ConcurrentDictionary<string, ChatterGroupStore>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Load()
|
||||||
|
{
|
||||||
|
var groups = new List<(string, string)>();
|
||||||
|
var data = new Dictionary<string, object>() { { "user", _userId } };
|
||||||
|
string sql = $"SELECT id, name, priority FROM \"Group\" WHERE \"userId\" = @user";
|
||||||
|
await _database.Execute(sql, data, (reader) =>
|
||||||
|
{
|
||||||
|
var id = reader.GetGuid(0).ToString();
|
||||||
|
var name = reader.GetString(1);
|
||||||
|
_store.Add(id, new Group()
|
||||||
|
{
|
||||||
|
Id = id,
|
||||||
|
UserId = _userId,
|
||||||
|
Name = name,
|
||||||
|
Priority = reader.GetInt32(2),
|
||||||
|
});
|
||||||
|
groups.Add((id, name));
|
||||||
|
});
|
||||||
|
_logger.Information($"Loaded {_store.Count} groups from database.");
|
||||||
|
|
||||||
|
// Load Chatter Groups
|
||||||
|
var chatterGroupTable = _configuration.Database.Tables["ChatterGroup"];
|
||||||
|
var groupChatters = groups.Select(group => new ChatterGroupStore(_userId, group.Item1, chatterGroupTable, _database, _logger)).ToArray();
|
||||||
|
|
||||||
|
List<Task> tasks = new List<Task>();
|
||||||
|
for (var i = 0; i < groups.Count; i++)
|
||||||
|
{
|
||||||
|
var store = groupChatters[i];
|
||||||
|
if (AUTO_GENERATED_GROUP_NAMES.All(n => n != groups[i].Item2))
|
||||||
|
tasks.Add(store.Load());
|
||||||
|
_chatters.Add(store.GroupId, store);
|
||||||
|
}
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Save()
|
||||||
|
{
|
||||||
|
List<Task> tasks = _chatters.Values.Select(c => c.Save()).ToList();
|
||||||
|
tasks.Add(base.Save());
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialAdd(string key, Group value)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||||
|
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.UserId, nameof(value.UserId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.Name, nameof(value.Name));
|
||||||
|
ArgumentNullException.ThrowIfNull(value.Priority, nameof(value.Priority));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialModify(string key, Group oldValue, Group newValue)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue, nameof(newValue));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.UserId, nameof(newValue.UserId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.Name, nameof(newValue.Name));
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue.Priority, nameof(newValue.Priority));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.UserId, newValue.UserId, nameof(oldValue.UserId));
|
||||||
|
if (AUTO_GENERATED_GROUP_NAMES.Any(s => s == oldValue.Name))
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.Name, newValue.Name, nameof(oldValue.Name));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnPostRemove(string key, Group value)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,137 +0,0 @@
|
|||||||
|
|
||||||
|
|
||||||
using System.Collections.Immutable;
|
|
||||||
|
|
||||||
namespace HermesSocketServer.Store
|
|
||||||
{
|
|
||||||
public abstract class GroupSaveStore<K, V> : IStore<K, V> where K : class where V : class
|
|
||||||
{
|
|
||||||
private readonly Serilog.ILogger _logger;
|
|
||||||
protected readonly IDictionary<K, V> _store;
|
|
||||||
protected readonly IList<K> _added;
|
|
||||||
protected readonly IList<K> _modified;
|
|
||||||
protected readonly IList<K> _deleted;
|
|
||||||
protected readonly object _lock;
|
|
||||||
|
|
||||||
|
|
||||||
public GroupSaveStore(Serilog.ILogger logger)
|
|
||||||
{
|
|
||||||
_logger = logger;
|
|
||||||
_store = new Dictionary<K, V>();
|
|
||||||
_added = new List<K>();
|
|
||||||
_modified = new List<K>();
|
|
||||||
_deleted = new List<K>();
|
|
||||||
_lock = new object();
|
|
||||||
}
|
|
||||||
|
|
||||||
public abstract Task Load();
|
|
||||||
protected abstract void OnInitialAdd(K key, V value);
|
|
||||||
protected abstract void OnInitialModify(K key, V value);
|
|
||||||
protected abstract void OnInitialRemove(K key);
|
|
||||||
public abstract Task<bool> Save();
|
|
||||||
|
|
||||||
public V? Get(K key)
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
if (_store.TryGetValue(key, out var value))
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IDictionary<K, V> Get()
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
return _store.ToImmutableDictionary();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool Modify(K? key, Action<V> action)
|
|
||||||
{
|
|
||||||
if (key == null)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
if (_store.TryGetValue(key, out V? value))
|
|
||||||
{
|
|
||||||
if (value == null)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
action(value);
|
|
||||||
if (!_added.Contains(key) && !_modified.Contains(key))
|
|
||||||
{
|
|
||||||
_modified.Add(key);
|
|
||||||
_logger.Information($"added key to _modified {key}");
|
|
||||||
}
|
|
||||||
OnInitialModify(key, value);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Remove(K? key)
|
|
||||||
{
|
|
||||||
if (key == null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
if (_store.Remove(key))
|
|
||||||
{
|
|
||||||
_logger.Information($"removed key from _deleted {key}");
|
|
||||||
OnInitialRemove(key);
|
|
||||||
if (!_added.Remove(key))
|
|
||||||
{
|
|
||||||
_modified.Remove(key);
|
|
||||||
_logger.Information($"removed key from _added & _modified {key}");
|
|
||||||
if (!_deleted.Contains(key))
|
|
||||||
{
|
|
||||||
_deleted.Add(key);
|
|
||||||
_logger.Information($"added key to _deleted {key}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool Set(K? key, V? value)
|
|
||||||
{
|
|
||||||
if (key == null || value == null)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
if (_store.TryGetValue(key, out V? fetched))
|
|
||||||
{
|
|
||||||
if (fetched != value)
|
|
||||||
{
|
|
||||||
OnInitialModify(key, value);
|
|
||||||
_store[key] = value;
|
|
||||||
if (!_added.Contains(key) && !_modified.Contains(key))
|
|
||||||
{
|
|
||||||
_modified.Add(key);
|
|
||||||
_logger.Information($"added key to _modified {key}");
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
OnInitialAdd(key, value);
|
|
||||||
_store.Add(key, value);
|
|
||||||
if (!_deleted.Remove(key) && !_added.Contains(key))
|
|
||||||
{
|
|
||||||
_added.Add(key);
|
|
||||||
_logger.Information($"added key to _added {key}");
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -2,12 +2,14 @@ namespace HermesSocketServer.Store
|
|||||||
{
|
{
|
||||||
public interface IStore<K, V>
|
public interface IStore<K, V>
|
||||||
{
|
{
|
||||||
|
bool Exists(K key);
|
||||||
V? Get(K key);
|
V? Get(K key);
|
||||||
IDictionary<K, V> Get();
|
IDictionary<K, V> Get();
|
||||||
Task Load();
|
Task Load();
|
||||||
bool Modify(K? key, Action<V> action);
|
bool Modify(K? key, Action<V> modify);
|
||||||
void Remove(K? key);
|
bool Modify(K? key, V value);
|
||||||
Task<bool> Save();
|
bool Remove(K? key, bool fromCascade = false);
|
||||||
bool Set(K? key, V? value);
|
Task Save();
|
||||||
|
bool Set(K? key, V value);
|
||||||
}
|
}
|
||||||
}
|
}
|
85
Store/Internal/AutoSavedStore.cs
Normal file
85
Store/Internal/AutoSavedStore.cs
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
|
||||||
|
|
||||||
|
using System.Collections.Immutable;
|
||||||
|
using HermesSocketLibrary.db;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Store.Internal
|
||||||
|
{
|
||||||
|
public abstract class AutoSavedStore<K, V> : GroupSaveStore<K, V> where K : class where V : class
|
||||||
|
{
|
||||||
|
private readonly GroupSaveSqlGenerator<V> _generator;
|
||||||
|
private readonly DatabaseTable _table;
|
||||||
|
private readonly Database _database;
|
||||||
|
private readonly Serilog.ILogger _logger;
|
||||||
|
|
||||||
|
|
||||||
|
public AutoSavedStore(DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||||
|
: base()
|
||||||
|
{
|
||||||
|
if (table.TypeMapping == null)
|
||||||
|
_generator = new GroupSaveSqlGenerator<V>(table.PropertyMapping, logger);
|
||||||
|
else
|
||||||
|
_generator = new GroupSaveSqlGenerator<V>(table.PropertyMapping, table.TypeMapping, logger);
|
||||||
|
_table = table;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Save()
|
||||||
|
{
|
||||||
|
var allColumns = _table.KeyColumns.Union(_table.DataColumns).ToArray();
|
||||||
|
var typeMapping = _table.TypeMapping ?? new Dictionary<string, string>();
|
||||||
|
|
||||||
|
await GenerateQuery(_added,
|
||||||
|
(size) => _generator.GeneratePreparedInsertSql(_table.TableName, size, allColumns, typeMapping),
|
||||||
|
async (query, _, values) => await _generator.DoPreparedStatement(_database, query, values, allColumns));
|
||||||
|
|
||||||
|
await GenerateQuery(_modified,
|
||||||
|
(size) => _generator.GeneratePreparedUpdateSql(_table.TableName, size, _table.KeyColumns, _table.DataColumns, typeMapping),
|
||||||
|
async (query, _, values) => await _generator.DoPreparedStatement(_database, query, values, allColumns));
|
||||||
|
|
||||||
|
await GenerateQuery(_deleted,
|
||||||
|
(size) => _generator.GeneratePreparedDeleteSql(_table.TableName, size, _table.KeyColumns, typeMapping),
|
||||||
|
async (query, keys, _) => await _generator.DoPreparedStatementRaw(_database, query, keys, _table.KeyColumns));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task GenerateQuery(IList<K> keys, Func<int, string> generate, Func<string, IEnumerable<K>, IEnumerable<V>, Task<int>> execute)
|
||||||
|
{
|
||||||
|
ImmutableList<K>? list = null;
|
||||||
|
_rwls.EnterUpgradeableReadLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!keys.Any())
|
||||||
|
return;
|
||||||
|
|
||||||
|
_rwls.EnterWriteLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
list = keys.ToImmutableList();
|
||||||
|
keys.Clear();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitWriteLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitUpgradeableReadLock();
|
||||||
|
}
|
||||||
|
|
||||||
|
var query = generate(list.Count);
|
||||||
|
var values = list.Select(id => _store[id]).Where(v => v != null);
|
||||||
|
int rowsAffected = await execute(query, list, values);
|
||||||
|
|
||||||
|
if (rowsAffected != list.Count)
|
||||||
|
{
|
||||||
|
_logger.Error($"Rows affected in database ({rowsAffected}) and the number of items that should be modified ({list.Count}) do not match: {query}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_logger.Information($"{rowsAffected} rows were affected by this query: {query}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
131
Store/Internal/ComplexAutoSavedStore.cs
Normal file
131
Store/Internal/ComplexAutoSavedStore.cs
Normal file
@ -0,0 +1,131 @@
|
|||||||
|
|
||||||
|
|
||||||
|
using System.Collections.Immutable;
|
||||||
|
using HermesSocketLibrary.db;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Store.Internal
|
||||||
|
{
|
||||||
|
public abstract class ComplexAutoSavedStore<K, V> : GroupSaveStore<K, V> where K : class where V : class
|
||||||
|
{
|
||||||
|
private readonly IList<V> _removedValues;
|
||||||
|
private readonly GroupSaveSqlGenerator<V> _generator;
|
||||||
|
private readonly DatabaseTable _table;
|
||||||
|
private readonly Database _database;
|
||||||
|
private readonly Serilog.ILogger _logger;
|
||||||
|
|
||||||
|
|
||||||
|
public ComplexAutoSavedStore(DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||||
|
: base()
|
||||||
|
{
|
||||||
|
if (table.KeyColumns.Length <= 1)
|
||||||
|
throw new InvalidOperationException($"Use AutoSavedStore instead due to a single key column [table name: {table.TableName}]");
|
||||||
|
|
||||||
|
_removedValues = new List<V>();
|
||||||
|
if (table.TypeMapping == null)
|
||||||
|
_generator = new GroupSaveSqlGenerator<V>(table.PropertyMapping, logger);
|
||||||
|
else
|
||||||
|
_generator = new GroupSaveSqlGenerator<V>(table.PropertyMapping, table.TypeMapping, logger);
|
||||||
|
_table = table;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Save()
|
||||||
|
{
|
||||||
|
var allColumns = _table.KeyColumns.Union(_table.DataColumns).ToArray();
|
||||||
|
var typeMapping = _table.TypeMapping ?? new Dictionary<string, string>();
|
||||||
|
|
||||||
|
await GenerateQuery(_added,
|
||||||
|
(size) => _generator.GeneratePreparedInsertSql(_table.TableName, size, allColumns, typeMapping),
|
||||||
|
async (query, _, values) => await _generator.DoPreparedStatement(_database, query, values, allColumns));
|
||||||
|
|
||||||
|
await GenerateQuery(_modified,
|
||||||
|
(size) => _generator.GeneratePreparedUpdateSql(_table.TableName, size, _table.KeyColumns, _table.DataColumns, typeMapping),
|
||||||
|
async (query, _, values) => await _generator.DoPreparedStatement(_database, query, values, allColumns));
|
||||||
|
|
||||||
|
await GenerateDeleteQuery(_deleted, _removedValues,
|
||||||
|
(size) => _generator.GeneratePreparedDeleteSql(_table.TableName, size, _table.KeyColumns, typeMapping),
|
||||||
|
async (query, list) => await _generator.DoPreparedStatement(_database, query, list, _table.KeyColumns));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task GenerateQuery(IList<K> keys, Func<int, string> generate, Func<string, IEnumerable<K>, IEnumerable<V?>, Task<int>> execute)
|
||||||
|
{
|
||||||
|
ImmutableList<K>? list = null;
|
||||||
|
_rwls.EnterUpgradeableReadLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!keys.Any())
|
||||||
|
return;
|
||||||
|
|
||||||
|
_rwls.EnterWriteLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
list = keys.ToImmutableList();
|
||||||
|
keys.Clear();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitWriteLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitUpgradeableReadLock();
|
||||||
|
}
|
||||||
|
|
||||||
|
var query = generate(list.Count);
|
||||||
|
var values = list.Select(id => _store[id]).Where(v => v != null);
|
||||||
|
int rowsAffected = await execute(query, list, values);
|
||||||
|
|
||||||
|
if (rowsAffected != list.Count)
|
||||||
|
{
|
||||||
|
_logger.Error($"Rows affected in database ({rowsAffected}) and the number of items that should be modified ({list.Count}) do not match: {query}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_logger.Information($"{rowsAffected} rows were affected by this query: {query}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task GenerateDeleteQuery(IList<K> keys, IList<V> values, Func<int, string> generate, Func<string, IEnumerable<V>, Task<int>> execute)
|
||||||
|
{
|
||||||
|
ImmutableList<V>? list = null;
|
||||||
|
_rwls.EnterUpgradeableReadLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!keys.Any() || !values.Any())
|
||||||
|
return;
|
||||||
|
|
||||||
|
_rwls.EnterWriteLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
list = values.ToImmutableList();
|
||||||
|
values.Clear();
|
||||||
|
keys.Clear();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitWriteLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitUpgradeableReadLock();
|
||||||
|
}
|
||||||
|
|
||||||
|
var query = generate(list.Count);
|
||||||
|
int rowsAffected = await execute(query, list);
|
||||||
|
|
||||||
|
if (rowsAffected != list.Count)
|
||||||
|
{
|
||||||
|
_logger.Error($"Rows affected in database ({rowsAffected}) and the number of items that should be modified ({list.Count}) do not match: {query}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_logger.Information($"{rowsAffected} rows were affected by this query: {query}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnPostRemove(K key, V value) => _removedValues.Add(value);
|
||||||
|
}
|
||||||
|
}
|
11
Store/Internal/DatabaseTable.cs
Normal file
11
Store/Internal/DatabaseTable.cs
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
namespace HermesSocketServer.Store.Internal
|
||||||
|
{
|
||||||
|
public class DatabaseTable
|
||||||
|
{
|
||||||
|
public required string TableName { get; set; }
|
||||||
|
public required string[] KeyColumns { get; set; }
|
||||||
|
public required string[] DataColumns { get; set; }
|
||||||
|
public required IDictionary<string, string> PropertyMapping { get; set; }
|
||||||
|
public IDictionary<string, string>? TypeMapping { get; set; }
|
||||||
|
}
|
||||||
|
}
|
204
Store/Internal/GroupSaveSqlGenerator.cs
Normal file
204
Store/Internal/GroupSaveSqlGenerator.cs
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
using System.Reflection;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HermesSocketLibrary.db;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Store.Internal
|
||||||
|
{
|
||||||
|
public class GroupSaveSqlGenerator<T>
|
||||||
|
{
|
||||||
|
private readonly IDictionary<string, PropertyInfo?> _columnPropertyRelations;
|
||||||
|
private readonly IDictionary<string, string> _columnTypes;
|
||||||
|
private readonly Serilog.ILogger _logger;
|
||||||
|
|
||||||
|
public GroupSaveSqlGenerator(IDictionary<string, string> columnsToProperties, Serilog.ILogger logger)
|
||||||
|
: this(columnsToProperties, new Dictionary<string, string>(), logger)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupSaveSqlGenerator(IDictionary<string, string> columnsToProperties, IDictionary<string, string> columnTypes, Serilog.ILogger logger)
|
||||||
|
{
|
||||||
|
var type = typeof(T);
|
||||||
|
_columnPropertyRelations = columnsToProperties.ToDictionary(p => p.Key, p => type.GetProperty(p.Value));
|
||||||
|
_columnTypes = columnTypes;
|
||||||
|
_logger = logger;
|
||||||
|
|
||||||
|
var nullProperties = _columnPropertyRelations.Where(p => p.Value == null)
|
||||||
|
.Select(p => columnsToProperties[p.Key]);
|
||||||
|
if (nullProperties.Any())
|
||||||
|
throw new ArgumentException("Some properties do not exist on the values given: " + string.Join(", ", nullProperties));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<int> DoPreparedStatement<V>(Database database, string sql, IEnumerable<V> values, string[] columns)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await database.Execute(sql, (c) =>
|
||||||
|
{
|
||||||
|
var valueCounter = 0;
|
||||||
|
foreach (var value in values)
|
||||||
|
{
|
||||||
|
foreach (var column in columns)
|
||||||
|
{
|
||||||
|
var propValue = _columnPropertyRelations[column]!.GetValue(value);
|
||||||
|
if (_columnTypes.Any() && _columnTypes.TryGetValue(column, out var type))
|
||||||
|
{
|
||||||
|
if (type == "jsonb")
|
||||||
|
propValue = JsonSerializer.Serialize(propValue);
|
||||||
|
}
|
||||||
|
c.Parameters.AddWithValue(column.ToLower() + valueCounter, propValue ?? DBNull.Value);
|
||||||
|
}
|
||||||
|
valueCounter++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.Error(ex, "Failed to execute a prepared statement: " + sql);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<int> DoPreparedStatementRaw<V>(Database database, string sql, IEnumerable<V> values, string[] columns)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await database.Execute(sql, (c) =>
|
||||||
|
{
|
||||||
|
var valueCounter = 0;
|
||||||
|
foreach (var value in values)
|
||||||
|
{
|
||||||
|
foreach (var column in columns)
|
||||||
|
{
|
||||||
|
object? propValue = value;
|
||||||
|
c.Parameters.AddWithValue(column.ToLower() + valueCounter, propValue ?? DBNull.Value);
|
||||||
|
}
|
||||||
|
valueCounter++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.Error(ex, "Failed to execute a prepared statement: " + sql);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public string GeneratePreparedInsertSql(string table, int rows, IEnumerable<string> columns, IDictionary<string, string> typeMapping)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(table))
|
||||||
|
throw new ArgumentException("Value is either null or whitespace-filled.", nameof(table));
|
||||||
|
if (columns == null)
|
||||||
|
throw new ArgumentNullException(nameof(columns));
|
||||||
|
if (!columns.Any())
|
||||||
|
throw new ArgumentException("Empty list given.", nameof(columns));
|
||||||
|
|
||||||
|
var ctp = columns.ToDictionary(c => c, c => _columnPropertyRelations[c]);
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.Append($"INSERT INTO \"{table}\" (\"{string.Join("\", \"", columns)}\") VALUES ");
|
||||||
|
for (var row = 0; row < rows; row++)
|
||||||
|
{
|
||||||
|
sb.Append("(");
|
||||||
|
foreach (var column in columns)
|
||||||
|
{
|
||||||
|
sb.Append('@')
|
||||||
|
.Append(column.ToLower())
|
||||||
|
.Append(row);
|
||||||
|
|
||||||
|
if (typeMapping.TryGetValue(column, out var type))
|
||||||
|
sb.Append("::\"")
|
||||||
|
.Append(type)
|
||||||
|
.Append("\"");
|
||||||
|
|
||||||
|
sb.Append(", ");
|
||||||
|
}
|
||||||
|
sb.Remove(sb.Length - 2, 2)
|
||||||
|
.Append("),");
|
||||||
|
}
|
||||||
|
sb.Remove(sb.Length - 1, 1)
|
||||||
|
.Append(';');
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string GeneratePreparedUpdateSql(string table, int rows, IEnumerable<string> keyColumns, IEnumerable<string> updateColumns, IDictionary<string, string> typeMapping)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(table))
|
||||||
|
throw new ArgumentException("Value is either null or whitespace-filled.", nameof(table));
|
||||||
|
if (keyColumns == null)
|
||||||
|
throw new ArgumentNullException(nameof(keyColumns));
|
||||||
|
if (!keyColumns.Any())
|
||||||
|
throw new ArgumentException("Empty list given.", nameof(keyColumns));
|
||||||
|
if (updateColumns == null)
|
||||||
|
throw new ArgumentNullException(nameof(updateColumns));
|
||||||
|
if (!updateColumns.Any())
|
||||||
|
throw new ArgumentException("Empty list given.", nameof(updateColumns));
|
||||||
|
|
||||||
|
var columns = keyColumns.Union(updateColumns);
|
||||||
|
var ctp = columns.ToDictionary(c => c, c => _columnPropertyRelations[c]);
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.Append($"UPDATE \"{table}\" as t SET {string.Join(", ", updateColumns.Select(c => "\"" + c + "\" = c.\"" + c + "\""))} FROM (VALUES ");
|
||||||
|
for (var row = 0; row < rows; row++)
|
||||||
|
{
|
||||||
|
sb.Append("(");
|
||||||
|
foreach (var column in columns)
|
||||||
|
{
|
||||||
|
sb.Append('@')
|
||||||
|
.Append(column)
|
||||||
|
.Append(row);
|
||||||
|
|
||||||
|
if (typeMapping.TryGetValue(column, out var type))
|
||||||
|
sb.Append("::\"")
|
||||||
|
.Append(type)
|
||||||
|
.Append("\"");
|
||||||
|
|
||||||
|
sb.Append(", ");
|
||||||
|
}
|
||||||
|
sb.Remove(sb.Length - 2, 2)
|
||||||
|
.Append("),");
|
||||||
|
}
|
||||||
|
sb.Remove(sb.Length - 1, 1)
|
||||||
|
.Append($") AS c(\"{string.Join("\", \"", columns)}\") WHERE ")
|
||||||
|
.Append(string.Join(" AND ", keyColumns.Select(c => "t.\"" + c + "\" = c.\"" + c + "\"")))
|
||||||
|
.Append(";");
|
||||||
|
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string GeneratePreparedDeleteSql(string table, int rows, IEnumerable<string> keyColumns, IDictionary<string, string> typeMapping)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(table))
|
||||||
|
throw new ArgumentException("Value is either null or whitespace-filled.", nameof(table));
|
||||||
|
if (keyColumns == null)
|
||||||
|
throw new ArgumentNullException(nameof(keyColumns));
|
||||||
|
if (!keyColumns.Any())
|
||||||
|
throw new ArgumentException("Empty list given.", nameof(keyColumns));
|
||||||
|
|
||||||
|
var ctp = keyColumns.ToDictionary(c => c, c => _columnPropertyRelations[c]);
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.Append($"DELETE FROM \"{table}\" WHERE (\"{string.Join("\", \"", keyColumns)}\") IN (");
|
||||||
|
for (var row = 0; row < rows; row++)
|
||||||
|
{
|
||||||
|
sb.Append("(");
|
||||||
|
foreach (var column in keyColumns)
|
||||||
|
{
|
||||||
|
sb.Append('@')
|
||||||
|
.Append(column)
|
||||||
|
.Append(row);
|
||||||
|
|
||||||
|
if (typeMapping.TryGetValue(column, out var type))
|
||||||
|
sb.Append("::\"")
|
||||||
|
.Append(type)
|
||||||
|
.Append("\"");
|
||||||
|
|
||||||
|
sb.Append(", ");
|
||||||
|
}
|
||||||
|
sb.Remove(sb.Length - 2, 2)
|
||||||
|
.Append("),");
|
||||||
|
}
|
||||||
|
sb.Remove(sb.Length - 1, 1)
|
||||||
|
.Append(");");
|
||||||
|
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
205
Store/Internal/GroupedSaveStore.cs
Normal file
205
Store/Internal/GroupedSaveStore.cs
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
|
||||||
|
|
||||||
|
using System.Collections.Immutable;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Store.Internal
|
||||||
|
{
|
||||||
|
public abstract class GroupSaveStore<K, V> : IStore<K, V> where K : class where V : class
|
||||||
|
{
|
||||||
|
protected readonly IDictionary<K, V> _store;
|
||||||
|
protected readonly IList<K> _added;
|
||||||
|
protected readonly IList<K> _modified;
|
||||||
|
protected readonly IList<K> _deleted;
|
||||||
|
protected readonly ReaderWriterLockSlim _rwls;
|
||||||
|
|
||||||
|
|
||||||
|
public GroupSaveStore()
|
||||||
|
{
|
||||||
|
_store = new Dictionary<K, V>();
|
||||||
|
_added = new List<K>();
|
||||||
|
_modified = new List<K>();
|
||||||
|
_deleted = new List<K>();
|
||||||
|
_rwls = new ReaderWriterLockSlim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public abstract Task Load();
|
||||||
|
protected abstract void OnInitialAdd(K key, V value);
|
||||||
|
protected abstract void OnInitialModify(K key, V value, V newValue);
|
||||||
|
protected abstract void OnPostRemove(K key, V value);
|
||||||
|
public abstract Task Save();
|
||||||
|
|
||||||
|
|
||||||
|
public bool Exists(K key)
|
||||||
|
{
|
||||||
|
_rwls.EnterReadLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return _store.ContainsKey(key);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitReadLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public V? Get(K key)
|
||||||
|
{
|
||||||
|
_rwls.EnterReadLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_store.TryGetValue(key, out var value))
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitReadLock();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IDictionary<K, V> Get()
|
||||||
|
{
|
||||||
|
_rwls.EnterReadLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return _store.ToImmutableDictionary();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitReadLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Modify(K? key, V value)
|
||||||
|
{
|
||||||
|
if (key == null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
_rwls.EnterUpgradeableReadLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_store.TryGetValue(key, out V? oldValue))
|
||||||
|
{
|
||||||
|
_rwls.EnterWriteLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OnInitialModify(key, oldValue, value);
|
||||||
|
_store[key] = value;
|
||||||
|
if (!_added.Contains(key) && !_modified.Contains(key))
|
||||||
|
{
|
||||||
|
_modified.Add(key);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitWriteLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitUpgradeableReadLock();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Modify(K? key, Action<V> modify)
|
||||||
|
{
|
||||||
|
if (key == null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
_rwls.EnterUpgradeableReadLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_store.TryGetValue(key, out V? value))
|
||||||
|
{
|
||||||
|
_rwls.EnterWriteLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
modify(value);
|
||||||
|
if (!_added.Contains(key) && !_modified.Contains(key))
|
||||||
|
{
|
||||||
|
_modified.Add(key);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitWriteLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitUpgradeableReadLock();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Remove(K? key, bool fromCascade = false)
|
||||||
|
{
|
||||||
|
if (key == null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
_rwls.EnterWriteLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_store.TryGetValue(key, out var value))
|
||||||
|
{
|
||||||
|
_store.Remove(key);
|
||||||
|
OnPostRemove(key, value);
|
||||||
|
if (!_added.Remove(key))
|
||||||
|
{
|
||||||
|
_modified.Remove(key);
|
||||||
|
if (!fromCascade && !_deleted.Contains(key))
|
||||||
|
{
|
||||||
|
_deleted.Add(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitWriteLock();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Set(K? key, V value)
|
||||||
|
{
|
||||||
|
if (key == null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
_rwls.EnterWriteLock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_store.TryGetValue(key, out V? fetched))
|
||||||
|
{
|
||||||
|
OnInitialModify(key, fetched, value);
|
||||||
|
_store[key] = value;
|
||||||
|
if (!_added.Contains(key) && !_modified.Contains(key))
|
||||||
|
{
|
||||||
|
_modified.Add(key);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
OnInitialAdd(key, value);
|
||||||
|
_store.Add(key, value);
|
||||||
|
if (!_deleted.Remove(key) && !_added.Contains(key))
|
||||||
|
{
|
||||||
|
_added.Add(key);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_rwls.ExitWriteLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,31 +1,25 @@
|
|||||||
using HermesSocketLibrary.db;
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Messages;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
namespace HermesSocketServer.Store
|
namespace HermesSocketServer.Store
|
||||||
{
|
{
|
||||||
public class PolicyStore : GroupSaveStore<string, Policy>
|
public class PolicyStore : AutoSavedStore<string, Policy>
|
||||||
{
|
{
|
||||||
private readonly string _userId;
|
private readonly string _userId;
|
||||||
|
private readonly IStore<string, Group> _groups;
|
||||||
private readonly Database _database;
|
private readonly Database _database;
|
||||||
private readonly Serilog.ILogger _logger;
|
private readonly Serilog.ILogger _logger;
|
||||||
private readonly GroupSaveSqlGenerator<Policy> _generator;
|
|
||||||
|
|
||||||
|
|
||||||
public PolicyStore(string userId, Database database, Serilog.ILogger logger) : base(logger)
|
public PolicyStore(string userId, DatabaseTable table, IStore<string, Group> groups, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
{
|
{
|
||||||
_userId = userId;
|
_userId = userId;
|
||||||
|
_groups = groups;
|
||||||
_database = database;
|
_database = database;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
|
||||||
var ctp = new Dictionary<string, string>
|
|
||||||
{
|
|
||||||
{ "id", "Id" },
|
|
||||||
{ "userId", "UserId" },
|
|
||||||
{ "groupId", "GroupId" },
|
|
||||||
{ "path", "Path" },
|
|
||||||
{ "count", "Usage" },
|
|
||||||
{ "timespan", "Span" },
|
|
||||||
};
|
|
||||||
_generator = new GroupSaveSqlGenerator<Policy>(ctp);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task Load()
|
public override async Task Load()
|
||||||
@ -34,15 +28,15 @@ namespace HermesSocketServer.Store
|
|||||||
string sql = $"SELECT id, \"groupId\", path, count, timespan FROM \"GroupPermissionPolicy\" WHERE \"userId\" = @user";
|
string sql = $"SELECT id, \"groupId\", path, count, timespan FROM \"GroupPermissionPolicy\" WHERE \"userId\" = @user";
|
||||||
await _database.Execute(sql, data, (reader) =>
|
await _database.Execute(sql, data, (reader) =>
|
||||||
{
|
{
|
||||||
string id = reader.GetString(0).ToString();
|
var id = reader.GetGuid(0);
|
||||||
_store.Add(id, new Policy()
|
_store.Add(id.ToString(), new Policy()
|
||||||
{
|
{
|
||||||
Id = id,
|
Id = id,
|
||||||
UserId = _userId,
|
UserId = _userId,
|
||||||
GroupId = reader.GetString(1),
|
GroupId = reader.GetGuid(1),
|
||||||
Path = reader.GetString(2),
|
Path = reader.GetString(2),
|
||||||
Usage = reader.GetInt32(3),
|
Usage = reader.GetInt32(3),
|
||||||
Span = TimeSpan.FromMilliseconds(reader.GetInt32(4)),
|
Span = reader.GetInt32(4),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
_logger.Information($"Loaded {_store.Count} policies from database.");
|
_logger.Information($"Loaded {_store.Count} policies from database.");
|
||||||
@ -50,56 +44,36 @@ namespace HermesSocketServer.Store
|
|||||||
|
|
||||||
protected override void OnInitialAdd(string key, Policy value)
|
protected override void OnInitialAdd(string key, Policy value)
|
||||||
{
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||||
|
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.UserId, nameof(value.UserId));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfEqual(value.GroupId, default, nameof(value.GroupId));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value.Usage, nameof(value.Usage));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(value.Usage, 99, nameof(value.Usage));
|
||||||
|
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 value)
|
protected override void OnInitialModify(string key, Policy oldValue, Policy newValue)
|
||||||
{
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue, nameof(newValue));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.UserId, nameof(newValue.UserId));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfEqual(newValue.GroupId, default, nameof(newValue.GroupId));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(newValue.Usage, nameof(newValue.Usage));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(newValue.Usage, 99, nameof(newValue.Usage));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(newValue.Span, nameof(newValue.Span));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfLessThan(newValue.Span, 1000, nameof(newValue.Span));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(newValue.Span, 86400, nameof(newValue.Span));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.Id, newValue.Id, nameof(oldValue.Id));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.UserId, newValue.UserId, nameof(oldValue.UserId));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnInitialRemove(string key)
|
protected override void OnPostRemove(string key, Policy value)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task<bool> Save()
|
|
||||||
{
|
|
||||||
int count = 0;
|
|
||||||
string sql = string.Empty;
|
|
||||||
|
|
||||||
if (_added.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _added.Count;
|
|
||||||
sql = _generator.GenerateInsertSql("GroupPermissionPolicy", _added.Select(a => _store[a]), ["id", "userId", "groupId", "path", "count", "timespan"]);
|
|
||||||
_added.Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.Debug($"GroupPermissionPolicy - Adding {count} rows to database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
if (_modified.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _modified.Count;
|
|
||||||
sql = _generator.GenerateUpdateSql("GroupPermissionPolicy", _modified.Select(m => _store[m]), ["id"], ["userId", "groupId", "path", "count", "timespan"]);
|
|
||||||
_modified.Clear();
|
|
||||||
}
|
|
||||||
_logger.Debug($"GroupPermissionPolicy - Modifying {count} rows in database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
if (_deleted.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _deleted.Count;
|
|
||||||
sql = _generator.GenerateDeleteSql("GroupPermissionPolicy", _deleted, ["id"]);
|
|
||||||
_deleted.Clear();
|
|
||||||
}
|
|
||||||
_logger.Debug($"GroupPermissionPolicy - Deleting {count} rows from database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
81
Store/RedemptionStore.cs
Normal file
81
Store/RedemptionStore.cs
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
|
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, IStore<string, RedeemableAction> actions, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
|
{
|
||||||
|
_userId = userId;
|
||||||
|
_actions = actions;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Load()
|
||||||
|
{
|
||||||
|
var data = new Dictionary<string, object>() { { "user", _userId } };
|
||||||
|
string sql = $"SELECT id, \"redemptionId\", \"order\", \"state\", \"actionName\" FROM \"Redemption\" WHERE \"userId\" = @user";
|
||||||
|
await _database.Execute(sql, data, (reader) =>
|
||||||
|
{
|
||||||
|
var id = reader.GetGuid(0);
|
||||||
|
_store.Add(id.ToString(), new Redemption()
|
||||||
|
{
|
||||||
|
Id = id.ToString(),
|
||||||
|
UserId = _userId,
|
||||||
|
RedemptionId = reader.GetString(1),
|
||||||
|
Order = reader.GetInt32(2),
|
||||||
|
State = reader.GetBoolean(3),
|
||||||
|
ActionName = reader.GetString(4),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
_logger.Information($"Loaded {_store.Count} redemptions from database.");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialAdd(string key, Redemption value)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||||
|
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.UserId, nameof(value.UserId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.RedemptionId, nameof(value.RedemptionId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.ActionName, nameof(value.ActionName));
|
||||||
|
ArgumentNullException.ThrowIfNull(value.State, nameof(value.State));
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue);
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.UserId, nameof(newValue.UserId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.RedemptionId, nameof(newValue.RedemptionId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.ActionName, nameof(newValue.ActionName));
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue.State, nameof(newValue.State));
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue.Order, nameof(newValue.Order));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegative(newValue.Order, nameof(newValue.Order));
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
70
Store/TTSFilterStore.cs
Normal file
70
Store/TTSFilterStore.cs
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
|
namespace HermesSocketServer.Store
|
||||||
|
{
|
||||||
|
public class TTSFilterStore : AutoSavedStore<string, TTSWordFilter>
|
||||||
|
{
|
||||||
|
private readonly string _userId;
|
||||||
|
private readonly Database _database;
|
||||||
|
private readonly Serilog.ILogger _logger;
|
||||||
|
|
||||||
|
|
||||||
|
public TTSFilterStore(string userId, DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
|
{
|
||||||
|
_userId = userId;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Load()
|
||||||
|
{
|
||||||
|
var data = new Dictionary<string, object>() { { "user", _userId } };
|
||||||
|
string sql = $"SELECT id, search, replace, flag FROM \"TtsWordFilter\" WHERE \"userId\" = @user";
|
||||||
|
await _database.Execute(sql, data, (reader) =>
|
||||||
|
{
|
||||||
|
var id = reader.GetString(0);
|
||||||
|
_store.Add(id.ToString(), new TTSWordFilter()
|
||||||
|
{
|
||||||
|
Id = id,
|
||||||
|
UserId = _userId,
|
||||||
|
Search = reader.GetString(1),
|
||||||
|
Replace = reader.GetString(2),
|
||||||
|
Flag = reader.GetInt32(3),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
_logger.Information($"Loaded {_store.Count} TTS filters from database.");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialAdd(string key, TTSWordFilter value)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||||
|
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.Id, nameof(value.Id));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.UserId, nameof(value.UserId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(value.Search, nameof(value.Search));
|
||||||
|
ArgumentNullException.ThrowIfNull(value.Replace, nameof(value.Replace));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegative(value.Flag, nameof(value.Flag));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(value.Flag, 2047, nameof(value.Flag));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialModify(string key, TTSWordFilter oldValue, TTSWordFilter newValue)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue, nameof(newValue));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.Id, nameof(newValue.Id));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.UserId, nameof(newValue.UserId));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.Search, nameof(newValue.Search));
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue.Replace, nameof(newValue.Replace));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegative(newValue.Flag, nameof(newValue.Flag));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(newValue.Flag, 2047, nameof(newValue.Flag));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.Id, newValue.Id, nameof(oldValue.Id));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.UserId, newValue.UserId, nameof(oldValue.UserId));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnPostRemove(string key, TTSWordFilter value)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,29 +1,20 @@
|
|||||||
using HermesSocketLibrary.db;
|
using HermesSocketLibrary.db;
|
||||||
using HermesSocketServer.Models;
|
using HermesSocketServer.Models;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
|
||||||
namespace HermesSocketServer.Store
|
namespace HermesSocketServer.Store
|
||||||
{
|
{
|
||||||
public class UserStore : GroupSaveStore<string, User>
|
public class UserStore : AutoSavedStore<string, User>
|
||||||
{
|
{
|
||||||
private readonly Database _database;
|
private readonly Database _database;
|
||||||
private readonly Serilog.ILogger _logger;
|
private readonly Serilog.ILogger _logger;
|
||||||
private readonly GroupSaveSqlGenerator<User> _generator;
|
|
||||||
|
|
||||||
|
|
||||||
public UserStore(Database database, Serilog.ILogger logger) : base(logger)
|
public UserStore([FromKeyedServices("User")] DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
{
|
{
|
||||||
_database = database;
|
_database = database;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
|
||||||
var ctp = new Dictionary<string, string>
|
|
||||||
{
|
|
||||||
{ "id", "Id" },
|
|
||||||
{ "name", "Name" },
|
|
||||||
{ "email", "Email" },
|
|
||||||
{ "role", "Role" },
|
|
||||||
{ "ttsDefaultVoice", "DefaultVoice" }
|
|
||||||
};
|
|
||||||
_generator = new GroupSaveSqlGenerator<User>(ctp);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task Load()
|
public override async Task Load()
|
||||||
@ -48,53 +39,12 @@ namespace HermesSocketServer.Store
|
|||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnInitialModify(string key, User value)
|
protected override void OnInitialModify(string key, User oldValue, User newValue)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnInitialRemove(string key)
|
protected override void OnPostRemove(string key, User value)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task<bool> Save()
|
|
||||||
{
|
|
||||||
int count = 0;
|
|
||||||
string sql = string.Empty;
|
|
||||||
|
|
||||||
if (_added.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _added.Count;
|
|
||||||
sql = _generator.GenerateInsertSql("User", _added.Select(a => _store[a]), ["id", "name", "email", "role", "ttsDefaultVoice"]);
|
|
||||||
_added.Clear();
|
|
||||||
}
|
|
||||||
_logger.Debug($"User - Adding {count} rows to database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
if (_modified.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _modified.Count;
|
|
||||||
sql = _generator.GenerateUpdateSql("User", _modified.Select(m => _store[m]), ["id"], ["name", "email", "role", "ttsDefaultVoice"]);
|
|
||||||
_modified.Clear();
|
|
||||||
}
|
|
||||||
_logger.Debug($"User - Modifying {count} rows in database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
if (_deleted.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _deleted.Count;
|
|
||||||
sql = _generator.GenerateDeleteSql("User", _deleted, ["id"]);
|
|
||||||
_deleted.Clear();
|
|
||||||
}
|
|
||||||
_logger.Debug($"User - Deleting {count} rows from database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
73
Store/VoiceStateStore.cs
Normal file
73
Store/VoiceStateStore.cs
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
using HermesSocketLibrary.db;
|
||||||
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
|
using HermesSocketServer.Validators;
|
||||||
|
|
||||||
|
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, DatabaseTable table, IStore<string, TTSVoice> voices, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
|
{
|
||||||
|
_userId = userId;
|
||||||
|
_voices = voices;
|
||||||
|
_database = database;
|
||||||
|
_logger = logger;
|
||||||
|
|
||||||
|
_idValidator = new VoiceIdValidator();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task Load()
|
||||||
|
{
|
||||||
|
var data = new Dictionary<string, object>() { { "user", _userId } };
|
||||||
|
string sql = "SELECT \"ttsVoiceId\", state FROM \"TtsVoiceState\" WHERE \"userId\" = @user";
|
||||||
|
await _database.Execute(sql, data, (reader) =>
|
||||||
|
{
|
||||||
|
string id = reader.GetString(0);
|
||||||
|
_store.Add(id, new TTSVoiceState()
|
||||||
|
{
|
||||||
|
Id = id,
|
||||||
|
Enabled = reader.GetBoolean(1),
|
||||||
|
UserId = _userId,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
_logger.Information($"Loaded {_store.Count} TTS voice states from database.");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialAdd(string key, TTSVoiceState value)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||||
|
_idValidator.Check(value.Id);
|
||||||
|
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue, nameof(newValue));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.Id, nameof(newValue.Id));
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(newValue.UserId, nameof(newValue.UserId));
|
||||||
|
ArgumentNullException.ThrowIfNull(newValue.Enabled, nameof(newValue.Enabled));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.Id, newValue.Id, nameof(oldValue.Id));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.UserId, newValue.UserId, nameof(oldValue.UserId));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfEqual(oldValue.Enabled, newValue.Enabled, nameof(oldValue.Enabled));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnPostRemove(string key, TTSVoiceState value)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,31 +1,25 @@
|
|||||||
using HermesSocketLibrary.db;
|
using HermesSocketLibrary.db;
|
||||||
using HermesSocketServer.Models;
|
using HermesSocketLibrary.Requests.Messages;
|
||||||
|
using HermesSocketServer.Store.Internal;
|
||||||
using HermesSocketServer.Validators;
|
using HermesSocketServer.Validators;
|
||||||
|
|
||||||
namespace HermesSocketServer.Store
|
namespace HermesSocketServer.Store
|
||||||
{
|
{
|
||||||
public class VoiceStore : GroupSaveStore<string, Voice>
|
public class VoiceStore : AutoSavedStore<string, TTSVoice>
|
||||||
{
|
{
|
||||||
private readonly VoiceIdValidator _idValidator;
|
private readonly VoiceIdValidator _idValidator;
|
||||||
private readonly VoiceNameValidator _nameValidator;
|
private readonly VoiceNameValidator _nameValidator;
|
||||||
private readonly Database _database;
|
private readonly Database _database;
|
||||||
private readonly Serilog.ILogger _logger;
|
private readonly Serilog.ILogger _logger;
|
||||||
private readonly GroupSaveSqlGenerator<Voice> _generator;
|
|
||||||
|
|
||||||
|
|
||||||
public VoiceStore(VoiceIdValidator voiceIdValidator, VoiceNameValidator voiceNameValidator, Database database, Serilog.ILogger logger) : base(logger)
|
public VoiceStore(VoiceIdValidator voiceIdValidator, VoiceNameValidator voiceNameValidator, [FromKeyedServices("Voice")] DatabaseTable table, Database database, Serilog.ILogger logger)
|
||||||
|
: base(table, database, logger)
|
||||||
{
|
{
|
||||||
_idValidator = voiceIdValidator;
|
_idValidator = voiceIdValidator;
|
||||||
_nameValidator = voiceNameValidator;
|
_nameValidator = voiceNameValidator;
|
||||||
_database = database;
|
_database = database;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
|
||||||
var ctp = new Dictionary<string, string>
|
|
||||||
{
|
|
||||||
{ "id", "Id" },
|
|
||||||
{ "name", "Name" }
|
|
||||||
};
|
|
||||||
_generator = new GroupSaveSqlGenerator<Voice>(ctp);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task Load()
|
public override async Task Load()
|
||||||
@ -34,7 +28,7 @@ namespace HermesSocketServer.Store
|
|||||||
await _database.Execute(sql, new Dictionary<string, object>(), (reader) =>
|
await _database.Execute(sql, new Dictionary<string, object>(), (reader) =>
|
||||||
{
|
{
|
||||||
string id = reader.GetString(0);
|
string id = reader.GetString(0);
|
||||||
_store.Add(id, new Voice()
|
_store.Add(id, new TTSVoice()
|
||||||
{
|
{
|
||||||
Id = id,
|
Id = id,
|
||||||
Name = reader.GetString(1),
|
Name = reader.GetString(1),
|
||||||
@ -43,61 +37,25 @@ namespace HermesSocketServer.Store
|
|||||||
_logger.Information($"Loaded {_store.Count} TTS voices from database.");
|
_logger.Information($"Loaded {_store.Count} TTS voices from database.");
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnInitialAdd(string key, Voice value)
|
protected override void OnInitialAdd(string key, TTSVoice value)
|
||||||
{
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key, nameof(key));
|
||||||
|
ArgumentNullException.ThrowIfNull(value, nameof(value));
|
||||||
_idValidator.Check(value.Id);
|
_idValidator.Check(value.Id);
|
||||||
_nameValidator.Check(value.Name);
|
_nameValidator.Check(value.Name);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnInitialModify(string key, Voice value)
|
protected override void OnInitialModify(string key, TTSVoice oldValue, TTSVoice newValue)
|
||||||
{
|
{
|
||||||
_nameValidator.Check(value.Name);
|
ArgumentNullException.ThrowIfNull(newValue, nameof(newValue));
|
||||||
|
_idValidator.Check(newValue.Id);
|
||||||
|
_nameValidator.Check(newValue.Name);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNotEqual(oldValue.Id, newValue.Id, nameof(oldValue.Id));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfEqual(oldValue.Name, newValue.Name, nameof(oldValue.Name));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnInitialRemove(string key)
|
protected override void OnPostRemove(string key, TTSVoice value)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task<bool> Save()
|
|
||||||
{
|
|
||||||
int count = 0;
|
|
||||||
string sql = string.Empty;
|
|
||||||
|
|
||||||
if (_added.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _added.Count;
|
|
||||||
sql = _generator.GenerateInsertSql("TtsVoice", _added.Select(a => _store[a]), ["id", "name"]);
|
|
||||||
_added.Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.Debug($"TtsVoice - Adding {count} rows to database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
if (_modified.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _modified.Count;
|
|
||||||
sql = _generator.GenerateUpdateSql("TtsVoice", _modified.Select(m => _store[m]), ["id"], ["name"]);
|
|
||||||
_modified.Clear();
|
|
||||||
}
|
|
||||||
_logger.Debug($"TtsVoice - Modifying {count} rows in database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
if (_deleted.Any())
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
count = _deleted.Count;
|
|
||||||
sql = _generator.GenerateDeleteSql("TtsVoice", _deleted, ["id"]);
|
|
||||||
_deleted.Clear();
|
|
||||||
}
|
|
||||||
_logger.Debug($"TtsVoice - Deleting {count} rows from database: {sql}");
|
|
||||||
await _database.ExecuteScalar(sql);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -5,9 +5,7 @@ namespace HermesSocketLibrary.db
|
|||||||
{
|
{
|
||||||
public class Database
|
public class Database
|
||||||
{
|
{
|
||||||
private NpgsqlDataSource _source;
|
private readonly NpgsqlDataSource _source;
|
||||||
private ServerConfiguration _configuration;
|
|
||||||
|
|
||||||
public NpgsqlDataSource DataSource { get => _source; }
|
public NpgsqlDataSource DataSource { get => _source; }
|
||||||
|
|
||||||
|
|
||||||
@ -19,10 +17,8 @@ namespace HermesSocketLibrary.db
|
|||||||
|
|
||||||
public async Task Execute(string sql, IDictionary<string, object>? values, Action<NpgsqlDataReader> reading)
|
public async Task Execute(string sql, IDictionary<string, object>? values, Action<NpgsqlDataReader> reading)
|
||||||
{
|
{
|
||||||
using (var connection = await _source.OpenConnectionAsync())
|
await using var connection = await _source.OpenConnectionAsync();
|
||||||
{
|
await using var command = new NpgsqlCommand(sql, connection);
|
||||||
using (var command = new NpgsqlCommand(sql, connection))
|
|
||||||
{
|
|
||||||
if (values != null)
|
if (values != null)
|
||||||
{
|
{
|
||||||
foreach (var entry in values)
|
foreach (var entry in values)
|
||||||
@ -30,75 +26,65 @@ namespace HermesSocketLibrary.db
|
|||||||
}
|
}
|
||||||
await command.PrepareAsync();
|
await command.PrepareAsync();
|
||||||
|
|
||||||
using (var reader = await command.ExecuteReaderAsync())
|
await using var reader = await command.ExecuteReaderAsync();
|
||||||
{
|
|
||||||
while (await reader.ReadAsync())
|
while (await reader.ReadAsync())
|
||||||
{
|
{
|
||||||
reading(reader);
|
reading(reader);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Execute(string sql, Action<NpgsqlCommand> action, Action<NpgsqlDataReader> reading)
|
public async Task Execute(string sql, Action<NpgsqlCommand> action, Action<NpgsqlDataReader> reading)
|
||||||
{
|
{
|
||||||
using (var connection = await _source.OpenConnectionAsync())
|
await using var connection = await _source.OpenConnectionAsync();
|
||||||
{
|
await using var command = new NpgsqlCommand(sql, connection);
|
||||||
using (var command = new NpgsqlCommand(sql, connection))
|
|
||||||
{
|
|
||||||
action(command);
|
action(command);
|
||||||
await command.PrepareAsync();
|
await command.PrepareAsync();
|
||||||
|
|
||||||
using (var reader = await command.ExecuteReaderAsync())
|
await using var reader = await command.ExecuteReaderAsync();
|
||||||
{
|
|
||||||
while (await reader.ReadAsync())
|
while (await reader.ReadAsync())
|
||||||
{
|
{
|
||||||
reading(reader);
|
reading(reader);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<int> Execute(string sql, IDictionary<string, object>? values)
|
public async Task<int> Execute(string sql, IDictionary<string, object>? values)
|
||||||
{
|
{
|
||||||
using (var connection = await _source.OpenConnectionAsync())
|
await using var connection = await _source.OpenConnectionAsync();
|
||||||
{
|
await using var command = new NpgsqlCommand(sql, connection);
|
||||||
using (var command = new NpgsqlCommand(sql, connection))
|
|
||||||
{
|
|
||||||
if (values != null)
|
if (values != null)
|
||||||
{
|
{
|
||||||
foreach (var entry in values)
|
foreach (var entry in values)
|
||||||
command.Parameters.AddWithValue(entry.Key, entry.Value);
|
command.Parameters.AddWithValue(entry.Key, entry.Value);
|
||||||
}
|
}
|
||||||
await command.PrepareAsync();
|
await command.PrepareAsync();
|
||||||
|
|
||||||
return await command.ExecuteNonQueryAsync();
|
return await command.ExecuteNonQueryAsync();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<int> Execute(string sql, Action<NpgsqlCommand> prepare)
|
public async Task<int> Execute(string sql, Action<NpgsqlCommand> prepare)
|
||||||
{
|
{
|
||||||
using (var connection = await _source.OpenConnectionAsync())
|
await using var connection = await _source.OpenConnectionAsync();
|
||||||
{
|
await using var command = new NpgsqlCommand(sql, connection);
|
||||||
using (var command = new NpgsqlCommand(sql, connection))
|
|
||||||
{
|
|
||||||
prepare(command);
|
prepare(command);
|
||||||
await command.PrepareAsync();
|
await command.PrepareAsync();
|
||||||
|
|
||||||
return await command.ExecuteNonQueryAsync();
|
return await command.ExecuteNonQueryAsync();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
public async Task<int> ExecuteTransaction(string sql, Action<NpgsqlCommand> prepare)
|
||||||
|
{
|
||||||
|
await using var connection = await _source.OpenConnectionAsync();
|
||||||
|
await using var transaction = await connection.BeginTransactionAsync();
|
||||||
|
await using var command = new NpgsqlCommand(sql, connection, transaction);
|
||||||
|
prepare(command);
|
||||||
|
await command.PrepareAsync();
|
||||||
|
var results = await command.ExecuteNonQueryAsync();
|
||||||
|
await transaction.CommitAsync();
|
||||||
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<object?> ExecuteScalar(string sql, IDictionary<string, object>? values = null)
|
public async Task<object?> ExecuteScalar(string sql, IDictionary<string, object>? values = null)
|
||||||
{
|
{
|
||||||
using (var connection = await _source.OpenConnectionAsync())
|
await using var connection = await _source.OpenConnectionAsync();
|
||||||
{
|
await using var command = new NpgsqlCommand(sql, connection);
|
||||||
using (var command = new NpgsqlCommand(sql, connection))
|
|
||||||
{
|
|
||||||
if (values != null)
|
if (values != null)
|
||||||
{
|
{
|
||||||
foreach (var entry in values)
|
foreach (var entry in values)
|
||||||
@ -106,24 +92,33 @@ namespace HermesSocketLibrary.db
|
|||||||
}
|
}
|
||||||
|
|
||||||
await command.PrepareAsync();
|
await command.PrepareAsync();
|
||||||
|
|
||||||
return await command.ExecuteScalarAsync();
|
return await command.ExecuteScalarAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<object?> ExecuteScalarTransaction(string sql, IDictionary<string, object>? values = null)
|
||||||
|
{
|
||||||
|
await using var connection = await _source.OpenConnectionAsync();
|
||||||
|
await using var transaction = await connection.BeginTransactionAsync();
|
||||||
|
await using var command = new NpgsqlCommand(sql, connection, transaction);
|
||||||
|
if (values != null)
|
||||||
|
{
|
||||||
|
foreach (var entry in values)
|
||||||
|
command.Parameters.AddWithValue(entry.Key, entry.Value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await command.PrepareAsync();
|
||||||
|
var results = await command.ExecuteScalarAsync();
|
||||||
|
await transaction.CommitAsync();
|
||||||
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<object?> ExecuteScalar(string sql, Action<NpgsqlCommand> action)
|
public async Task<object?> ExecuteScalar(string sql, Action<NpgsqlCommand> action)
|
||||||
{
|
{
|
||||||
using (var connection = await _source.OpenConnectionAsync())
|
await using var connection = await _source.OpenConnectionAsync();
|
||||||
{
|
await using var command = new NpgsqlCommand(sql, connection);
|
||||||
using (var command = new NpgsqlCommand(sql, connection))
|
|
||||||
{
|
|
||||||
action(command);
|
action(command);
|
||||||
await command.PrepareAsync();
|
await command.PrepareAsync();
|
||||||
|
|
||||||
return await command.ExecuteScalarAsync();
|
return await command.ExecuteScalarAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
Reference in New Issue
Block a user