Retire more IDataStore methods

This commit is contained in:
Ske 2020-06-29 14:54:11 +02:00
parent 9c1efc7886
commit 467ce78522
8 changed files with 54 additions and 152 deletions

View File

@ -1,5 +1,7 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Dapper;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -15,13 +17,11 @@ namespace PluralKit.API
[Route( "v{version:apiVersion}/m" )] [Route( "v{version:apiVersion}/m" )]
public class MemberController: ControllerBase public class MemberController: ControllerBase
{ {
private IDataStore _data;
private IDatabase _db; private IDatabase _db;
private IAuthorizationService _auth; private IAuthorizationService _auth;
public MemberController(IDataStore data, IAuthorizationService auth, IDatabase db) public MemberController(IAuthorizationService auth, IDatabase db)
{ {
_data = data;
_auth = auth; _auth = auth;
_db = db; _db = db;
} }
@ -29,7 +29,7 @@ namespace PluralKit.API
[HttpGet("{hid}")] [HttpGet("{hid}")]
public async Task<ActionResult<JObject>> GetMember(string hid) public async Task<ActionResult<JObject>> GetMember(string hid)
{ {
var member = await _data.GetMemberByHid(hid); var member = await _db.Execute(conn => conn.QueryMemberByHid(hid));
if (member == null) return NotFound("Member not found."); if (member == null) return NotFound("Member not found.");
return Ok(member.ToJson(User.ContextFor(member))); return Ok(member.ToJson(User.ContextFor(member)));
@ -40,16 +40,17 @@ namespace PluralKit.API
public async Task<ActionResult<JObject>> PostMember([FromBody] JObject properties) public async Task<ActionResult<JObject>> PostMember([FromBody] JObject properties)
{ {
var system = User.CurrentSystem(); var system = User.CurrentSystem();
if (!properties.ContainsKey("name")) if (!properties.ContainsKey("name"))
return BadRequest("Member name must be specified."); return BadRequest("Member name must be specified.");
await using var conn = await _db.Obtain();
// Enforce per-system member limit // Enforce per-system member limit
var memberCount = await _data.GetSystemMemberCount(system, true); var memberCount = await conn.QuerySingleAsync<int>("select count(*) from members where system = @System", new {System = system});
if (memberCount >= Limits.MaxMemberCount) if (memberCount >= Limits.MaxMemberCount)
return BadRequest($"Member limit reached ({memberCount} / {Limits.MaxMemberCount})."); return BadRequest($"Member limit reached ({memberCount} / {Limits.MaxMemberCount}).");
var member = await _data.CreateMember(system, properties.Value<string>("name")); var member = await conn.CreateMember(system, properties.Value<string>("name"));
MemberPatch patch; MemberPatch patch;
try try
{ {
@ -60,15 +61,17 @@ namespace PluralKit.API
return BadRequest(e.Message); return BadRequest(e.Message);
} }
var newMember = await _db.Execute(conn => conn.UpdateMember(member.Id, patch)); member = await conn.UpdateMember(member.Id, patch);
return Ok(member.ToJson(User.ContextFor(newMember))); return Ok(member.ToJson(User.ContextFor(member)));
} }
[HttpPatch("{hid}")] [HttpPatch("{hid}")]
[Authorize] [Authorize]
public async Task<ActionResult<JObject>> PatchMember(string hid, [FromBody] JObject changes) public async Task<ActionResult<JObject>> PatchMember(string hid, [FromBody] JObject changes)
{ {
var member = await _data.GetMemberByHid(hid); await using var conn = await _db.Obtain();
var member = await conn.QueryMemberByHid(hid);
if (member == null) return NotFound("Member not found."); if (member == null) return NotFound("Member not found.");
var res = await _auth.AuthorizeAsync(User, member, "EditMember"); var res = await _auth.AuthorizeAsync(User, member, "EditMember");
@ -84,7 +87,7 @@ namespace PluralKit.API
return BadRequest(e.Message); return BadRequest(e.Message);
} }
var newMember = await _db.Execute(conn => conn.UpdateMember(member.Id, patch)); var newMember = await conn.UpdateMember(member.Id, patch);
return Ok(member.ToJson(User.ContextFor(newMember))); return Ok(member.ToJson(User.ContextFor(newMember)));
} }
@ -92,13 +95,15 @@ namespace PluralKit.API
[Authorize] [Authorize]
public async Task<ActionResult> DeleteMember(string hid) public async Task<ActionResult> DeleteMember(string hid)
{ {
var member = await _data.GetMemberByHid(hid); await using var conn = await _db.Obtain();
var member = await conn.QueryMemberByHid(hid);
if (member == null) return NotFound("Member not found."); if (member == null) return NotFound("Member not found.");
var res = await _auth.AuthorizeAsync(User, member, "EditMember"); var res = await _auth.AuthorizeAsync(User, member, "EditMember");
if (!res.Succeeded) return Unauthorized($"Member '{hid}' is not part of your system."); if (!res.Succeeded) return Unauthorized($"Member '{hid}' is not part of your system.");
await _data.DeleteMember(member); await conn.DeleteMember(member.Id);
return Ok(); return Ok();
} }
} }

View File

@ -32,13 +32,15 @@ namespace PluralKit.Bot
if (!await ctx.PromptYesNo(msg)) throw new PKError("Member creation cancelled."); if (!await ctx.PromptYesNo(msg)) throw new PKError("Member creation cancelled.");
} }
await using var conn = await _db.Obtain();
// Enforce per-system member limit // Enforce per-system member limit
var memberCount = await _data.GetSystemMemberCount(ctx.System.Id, true); var memberCount = await conn.GetSystemMemberCount(ctx.System.Id);
if (memberCount >= Limits.MaxMemberCount) if (memberCount >= Limits.MaxMemberCount)
throw Errors.MemberLimitReachedError; throw Errors.MemberLimitReachedError;
// Create the member // Create the member
var member = await _data.CreateMember(ctx.System.Id, memberName); var member = await conn.CreateMember(ctx.System.Id, memberName);
memberCount++; memberCount++;
// Send confirmation and space hint // Send confirmation and space hint

View File

@ -28,13 +28,15 @@ namespace PluralKit.Bot {
public async Task<DiscordEmbed> CreateSystemEmbed(DiscordClient client, PKSystem system, LookupContext ctx) { public async Task<DiscordEmbed> CreateSystemEmbed(DiscordClient client, PKSystem system, LookupContext ctx)
var accounts = await _data.GetSystemAccounts(system); {
await using var conn = await _db.Obtain();
// Fetch/render info for all accounts simultaneously // Fetch/render info for all accounts simultaneously
var accounts = await conn.GetLinkedAccounts(system.Id);
var users = await Task.WhenAll(accounts.Select(async uid => (await client.GetUserAsync(uid))?.NameAndMention() ?? $"(deleted account {uid})")); var users = await Task.WhenAll(accounts.Select(async uid => (await client.GetUserAsync(uid))?.NameAndMention() ?? $"(deleted account {uid})"));
var memberCount = await _data.GetSystemMemberCount(system.Id, false); var memberCount = await conn.GetSystemMemberCount(system.Id, PrivacyLevel.Public);
var eb = new DiscordEmbedBuilder() var eb = new DiscordEmbedBuilder()
.WithColor(DiscordUtils.Gray) .WithColor(DiscordUtils.Gray)
.WithTitle(system.Name ?? null) .WithTitle(system.Name ?? null)

View File

@ -1,10 +1,10 @@
#nullable enable #nullable enable
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Dapper; using Dapper;
using PluralKit.Core;
namespace PluralKit.Core namespace PluralKit.Core
{ {
public static class ModelQueryExt public static class ModelQueryExt
@ -12,9 +12,23 @@ namespace PluralKit.Core
public static Task<PKSystem?> QuerySystem(this IPKConnection conn, SystemId id) => public static Task<PKSystem?> QuerySystem(this IPKConnection conn, SystemId id) =>
conn.QueryFirstOrDefaultAsync<PKSystem?>("select * from systems where id = @id", new {id}); conn.QueryFirstOrDefaultAsync<PKSystem?>("select * from systems where id = @id", new {id});
public static Task<int> GetSystemMemberCount(this IPKConnection conn, SystemId id, PrivacyLevel? privacyFilter = null)
{
var query = new StringBuilder("select count(*) from members where system = @Id");
if (privacyFilter != null)
query.Append($" and member_visibility = {(int) privacyFilter.Value}");
return conn.QuerySingleAsync<int>(query.ToString(), new {Id = id});
}
public static Task<IEnumerable<ulong>> GetLinkedAccounts(this IPKConnection conn, SystemId id) =>
conn.QueryAsync<ulong>("select uid from accounts where system = @Id", new {Id = id});
public static Task<PKMember?> QueryMember(this IPKConnection conn, MemberId id) => public static Task<PKMember?> QueryMember(this IPKConnection conn, MemberId id) =>
conn.QueryFirstOrDefaultAsync<PKMember?>("select * from members where id = @id", new {id}); conn.QueryFirstOrDefaultAsync<PKMember?>("select * from members where id = @id", new {id});
public static Task<PKMember?> QueryMemberByHid(this IPKConnection conn, string hid) =>
conn.QueryFirstOrDefaultAsync<PKMember?>("select * from members where hid = @hid", new {hid = hid.ToLowerInvariant()});
public static Task<GuildConfig> QueryOrInsertGuildConfig(this IPKConnection conn, ulong guild) => public static Task<GuildConfig> QueryOrInsertGuildConfig(this IPKConnection conn, ulong guild) =>
conn.QueryFirstAsync<GuildConfig>("insert into servers (id) values (@guild) on conflict (id) do update set id = @guild returning *", new {guild}); conn.QueryFirstAsync<GuildConfig>("insert into servers (id) values (@guild) on conflict (id) do update set id = @guild returning *", new {guild});

View File

@ -17,6 +17,11 @@ namespace PluralKit.Core
public static Task DeleteSystem(this IPKConnection conn, SystemId id) => public static Task DeleteSystem(this IPKConnection conn, SystemId id) =>
conn.ExecuteAsync("delete from systems where id = @Id", new {Id = id}); conn.ExecuteAsync("delete from systems where id = @Id", new {Id = id});
public static Task<PKMember> CreateMember(this IPKConnection conn, SystemId system, string memberName) =>
conn.QueryFirstAsync<PKMember>(
"insert into members (hid, system, name) values (find_free_member_hid(), @SystemId, @Name) returning *",
new {SystemId = system, Name = memberName});
public static Task<PKMember> UpdateMember(this IPKConnection conn, MemberId id, MemberPatch patch) public static Task<PKMember> UpdateMember(this IPKConnection conn, MemberId id, MemberPatch patch)
{ {
var (query, pms) = patch.Apply(new UpdateQueryBuilder("members", "id = @id")) var (query, pms) = patch.Apply(new UpdateQueryBuilder("members", "id = @id"))

View File

@ -131,7 +131,7 @@ namespace PluralKit.Core
{ {
// Tally up the members that didn't exist before, and check member count on import // Tally up the members that didn't exist before, and check member count on import
// If creating the unmatched members would put us over the member limit, abort before creating any members // If creating the unmatched members would put us over the member limit, abort before creating any members
var memberCountBefore = await _data.GetSystemMemberCount(system.Id, true); var memberCountBefore = await conn.GetSystemMemberCount(system.Id);
var membersToAdd = data.Members.Count(m => imp.IsNewMember(m.Id, m.Name)); var membersToAdd = data.Members.Count(m => imp.IsNewMember(m.Id, m.Name));
if (memberCountBefore + membersToAdd > Limits.MaxMemberCount) if (memberCountBefore + membersToAdd > Limits.MaxMemberCount)
{ {

View File

@ -63,24 +63,12 @@ namespace PluralKit.Core {
/// <returns>The <see cref="PKSystem"/> with the given linked account, or null if no system was found.</returns> /// <returns>The <see cref="PKSystem"/> with the given linked account, or null if no system was found.</returns>
Task<PKSystem> GetSystemByAccount(ulong linkedAccount); Task<PKSystem> GetSystemByAccount(ulong linkedAccount);
/// <summary>
/// Gets a system by its API token.
/// </summary>
/// <returns>The <see cref="PKSystem"/> with the given API token, or null if no corresponding system was found.</returns>
Task<PKSystem> GetSystemByToken(string apiToken);
/// <summary> /// <summary>
/// Gets the Discord account IDs linked to a system. /// Gets the Discord account IDs linked to a system.
/// </summary> /// </summary>
/// <returns>An enumerable of Discord account IDs linked to this system.</returns> /// <returns>An enumerable of Discord account IDs linked to this system.</returns>
Task<IEnumerable<ulong>> GetSystemAccounts(PKSystem system); Task<IEnumerable<ulong>> GetSystemAccounts(PKSystem system);
/// <summary>
/// Gets the member count of a system.
/// </summary>
/// <param name="includePrivate">Whether the returned count should include private members.</param>
Task<int> GetSystemMemberCount(SystemId system, bool includePrivate);
/// <summary> /// <summary>
/// Creates a system, auto-generating its corresponding IDs. /// Creates a system, auto-generating its corresponding IDs.
/// </summary> /// </summary>
@ -132,28 +120,6 @@ namespace PluralKit.Core {
/// <returns>An enumerable of <see cref="PKMember"/> structs representing each member in the system, in no particular order.</returns> /// <returns>An enumerable of <see cref="PKMember"/> structs representing each member in the system, in no particular order.</returns>
IAsyncEnumerable<PKMember> GetSystemMembers(PKSystem system, bool orderByName = false); IAsyncEnumerable<PKMember> GetSystemMembers(PKSystem system, bool orderByName = false);
/// <summary>
/// Creates a member, auto-generating its corresponding IDs.
/// </summary>
/// <param name="system">The system in which to create the member.</param>
/// <param name="name">The name of the member to create.</param>
/// <returns>The created system model.</returns>
Task<PKMember> CreateMember(SystemId system, string name);
/// <summary>
/// Saves the information within the given <see cref="PKMember"/> struct to the data store.
/// </summary>
Task SaveMember(PKMember member);
/// <summary>
/// Deletes the given member from the database.
/// </summary>
/// <para>
/// This will remove this member from any switches it's involved in, as well as all the messages
/// proxied by this member.
/// </para>
Task DeleteMember(PKMember member);
/// <summary> /// <summary>
/// Gets a message and its information by its ID. /// Gets a message and its information by its ID.
/// </summary> /// </summary>

View File

@ -19,23 +19,6 @@ namespace PluralKit.Core {
_logger = logger; _logger = logger;
} }
public async Task<IEnumerable<PKMember>> GetConflictingProxies(PKSystem system, ProxyTag tag)
{
using (var conn = await _conn.Obtain())
// return await conn.QueryAsync<PKMember>("select * from (select *, (unnest(proxy_tags)).prefix as prefix, (unnest(proxy_tags)).suffix as suffix from members where system = @System) as _ where prefix ilike @Prefix and suffix ilike @Suffix", new
// {
// System = system.Id,
// Prefix = tag.Prefix.Replace("%", "\\%") + "%",
// Suffix = "%" + tag.Suffix.Replace("%", "\\%")
// });
return await conn.QueryAsync<PKMember>("select * from (select *, (unnest(proxy_tags)).prefix as prefix, (unnest(proxy_tags)).suffix as suffix from members where system = @System) as _ where prefix = @Prefix and suffix = @Suffix", new
{
System = system.Id,
Prefix = tag.Prefix,
Suffix = tag.Suffix
});
}
public async Task<PKSystem> CreateSystem(string systemName = null) { public async Task<PKSystem> CreateSystem(string systemName = null) {
PKSystem system; PKSystem system;
using (var conn = await _conn.Obtain()) using (var conn = await _conn.Obtain())
@ -72,35 +55,6 @@ namespace PluralKit.Core {
return await conn.QuerySingleOrDefaultAsync<PKSystem>("select * from systems where systems.hid = @Hid", new { Hid = hid.ToLower() }); return await conn.QuerySingleOrDefaultAsync<PKSystem>("select * from systems where systems.hid = @Hid", new { Hid = hid.ToLower() });
} }
public async Task<PKSystem> GetSystemByToken(string token) {
using (var conn = await _conn.Obtain())
return await conn.QuerySingleOrDefaultAsync<PKSystem>("select * from systems where token = @Token", new { Token = token });
}
public async Task<PKSystem> GetSystemById(int id)
{
using (var conn = await _conn.Obtain())
return await conn.QuerySingleOrDefaultAsync<PKSystem>("select * from systems where id = @Id", new { Id = id });
}
public async Task SaveSystem(PKSystem system) {
using (var conn = await _conn.Obtain())
await conn.ExecuteAsync("update systems set name = @Name, description = @Description, tag = @Tag, avatar_url = @AvatarUrl, token = @Token, ui_tz = @UiTz, description_privacy = @DescriptionPrivacy, member_list_privacy = @MemberListPrivacy, front_privacy = @FrontPrivacy, front_history_privacy = @FrontHistoryPrivacy, pings_enabled = @PingsEnabled where id = @Id", system);
_logger.Information("Updated system {@System}", system);
}
public async Task DeleteSystem(PKSystem system)
{
using var conn = await _conn.Obtain();
// Fetch the list of accounts *before* deletion so we can cache-bust all of those
var accounts = (await conn.QueryAsync<ulong>("select uid from accounts where system = @Id", system)).ToArray();
await conn.ExecuteAsync("delete from systems where id = @Id", system);
_logger.Information("Deleted system {System}", system.Id);
}
public async Task<IEnumerable<ulong>> GetSystemAccounts(PKSystem system) public async Task<IEnumerable<ulong>> GetSystemAccounts(PKSystem system)
{ {
using (var conn = await _conn.Obtain()) using (var conn = await _conn.Obtain())
@ -113,23 +67,6 @@ namespace PluralKit.Core {
await conn.ExecuteAsync("delete from switches where system = @Id", system); await conn.ExecuteAsync("delete from switches where system = @Id", system);
} }
public async Task<PKMember> CreateMember(SystemId system, string name) {
PKMember member;
using (var conn = await _conn.Obtain())
member = await conn.QuerySingleAsync<PKMember>("insert into members (hid, system, name) values (find_free_member_hid(), @SystemId, @Name) returning *", new {
SystemID = system,
Name = name
});
_logger.Information("Created member {Member}", member.Id);
return member;
}
public async Task<PKMember> GetMemberById(MemberId id) {
using (var conn = await _conn.Obtain())
return await conn.QuerySingleOrDefaultAsync<PKMember>("select * from members where id = @Id", new { Id = id });
}
public async Task<PKMember> GetMemberByHid(string hid) { public async Task<PKMember> GetMemberByHid(string hid) {
using (var conn = await _conn.Obtain()) using (var conn = await _conn.Obtain())
return await conn.QuerySingleOrDefaultAsync<PKMember>("select * from members where hid = @Hid", new { Hid = hid.ToLower() }); return await conn.QuerySingleOrDefaultAsync<PKMember>("select * from members where hid = @Hid", new { Hid = hid.ToLower() });
@ -154,35 +91,6 @@ namespace PluralKit.Core {
return _conn.QueryStreamAsync<PKMember>(sql, new { SystemID = system.Id }); return _conn.QueryStreamAsync<PKMember>(sql, new { SystemID = system.Id });
} }
public async Task SaveMember(PKMember member) {
using (var conn = await _conn.Obtain())
await conn.ExecuteAsync("update members set name = @Name, display_name = @DisplayName, description = @Description, color = @Color, avatar_url = @AvatarUrl, birthday = @Birthday, pronouns = @Pronouns, proxy_tags = @ProxyTags, keep_proxy = @KeepProxy, member_visibility = @MemberVisibility, description_privacy = @DescriptionPrivacy, name_privacy = @NamePrivacy, avatar_privacy = @AvatarPrivacy, birthday_privacy = @BirthdayPrivacy, pronoun_privacy = @PronounPrivacy, metadata_privacy = @MetadataPrivacy where id = @Id", member);
_logger.Information("Updated member {@Member}", member);
}
public async Task DeleteMember(PKMember member) {
using (var conn = await _conn.Obtain())
await conn.ExecuteAsync("delete from members where id = @Id", member);
_logger.Information("Deleted member {@Member}", member);
}
public async Task<int> GetSystemMemberCount(SystemId id, bool includePrivate)
{
var query = "select count(*) from members where system = @Id";
if (!includePrivate) query += " and member_visibility = 1"; // 1 = public
using (var conn = await _conn.Obtain())
return await conn.ExecuteScalarAsync<int>(query, new { id });
}
public async Task<ulong> GetTotalMembers()
{
using (var conn = await _conn.Obtain())
return await conn.ExecuteScalarAsync<ulong>("select count(id) from members");
}
public async Task AddMessage(IPKConnection conn, ulong senderId, ulong guildId, ulong channelId, ulong postedMessageId, ulong triggerMessageId, MemberId proxiedMemberId) { public async Task AddMessage(IPKConnection conn, ulong senderId, ulong guildId, ulong channelId, ulong postedMessageId, ulong triggerMessageId, MemberId proxiedMemberId) {
// "on conflict do nothing" in the (pretty rare) case of duplicate events coming in from Discord, which would lead to a DB error before // "on conflict do nothing" in the (pretty rare) case of duplicate events coming in from Discord, which would lead to a DB error before
await conn.ExecuteAsync("insert into messages(mid, guild, channel, member, sender, original_mid) values(@MessageId, @GuildId, @ChannelId, @MemberId, @SenderId, @OriginalMid) on conflict do nothing", new { await conn.ExecuteAsync("insert into messages(mid, guild, channel, member, sender, original_mid) values(@MessageId, @GuildId, @ChannelId, @MemberId, @SenderId, @OriginalMid) on conflict do nothing", new {