Finally retire the PKMember setters!

This commit is contained in:
Ske 2020-06-29 14:15:30 +02:00
parent 281b669391
commit c5697b33e2
9 changed files with 94 additions and 86 deletions

View File

@ -85,60 +85,64 @@ namespace PluralKit.API
return o; return o;
} }
public static void ApplyJson(this PKMember member, JObject o) public static MemberPatch ToMemberPatch(JObject o)
{ {
var patch = new MemberPatch();
if (o.ContainsKey("name") && o["name"].Type == JTokenType.Null) if (o.ContainsKey("name") && o["name"].Type == JTokenType.Null)
throw new JsonModelParseError("Member name can not be set to null."); throw new JsonModelParseError("Member name can not be set to null.");
if (o.ContainsKey("name")) member.Name = o.Value<string>("name").BoundsCheckField(Limits.MaxMemberNameLength, "Member name"); if (o.ContainsKey("name")) patch.Name = o.Value<string>("name").BoundsCheckField(Limits.MaxMemberNameLength, "Member name");
if (o.ContainsKey("color")) member.Color = o.Value<string>("color").NullIfEmpty()?.ToLower(); if (o.ContainsKey("color")) patch.Color = o.Value<string>("color").NullIfEmpty()?.ToLower();
if (o.ContainsKey("display_name")) member.DisplayName = o.Value<string>("display_name").NullIfEmpty().BoundsCheckField(Limits.MaxMemberNameLength, "Member display name"); if (o.ContainsKey("display_name")) patch.DisplayName = o.Value<string>("display_name").NullIfEmpty().BoundsCheckField(Limits.MaxMemberNameLength, "Member display name");
if (o.ContainsKey("avatar_url")) member.AvatarUrl = o.Value<string>("avatar_url").NullIfEmpty().BoundsCheckField(Limits.MaxUriLength, "Member avatar URL"); if (o.ContainsKey("avatar_url")) patch.AvatarUrl = o.Value<string>("avatar_url").NullIfEmpty().BoundsCheckField(Limits.MaxUriLength, "Member avatar URL");
if (o.ContainsKey("birthday")) if (o.ContainsKey("birthday"))
{ {
var str = o.Value<string>("birthday").NullIfEmpty(); var str = o.Value<string>("birthday").NullIfEmpty();
var res = DateTimeFormats.DateExportFormat.Parse(str); var res = DateTimeFormats.DateExportFormat.Parse(str);
if (res.Success) member.Birthday = res.Value; if (res.Success) patch.Birthday = res.Value;
else if (str == null) member.Birthday = null; else if (str == null) patch.Birthday = null;
else throw new JsonModelParseError("Could not parse member birthday."); else throw new JsonModelParseError("Could not parse member birthday.");
} }
if (o.ContainsKey("pronouns")) member.Pronouns = o.Value<string>("pronouns").NullIfEmpty().BoundsCheckField(Limits.MaxPronounsLength, "Member pronouns"); if (o.ContainsKey("pronouns")) patch.Pronouns = o.Value<string>("pronouns").NullIfEmpty().BoundsCheckField(Limits.MaxPronounsLength, "Member pronouns");
if (o.ContainsKey("description")) member.Description = o.Value<string>("description").NullIfEmpty().BoundsCheckField(Limits.MaxDescriptionLength, "Member descriptoin"); if (o.ContainsKey("description")) patch.Description = o.Value<string>("description").NullIfEmpty().BoundsCheckField(Limits.MaxDescriptionLength, "Member descriptoin");
if (o.ContainsKey("keep_proxy")) member.KeepProxy = o.Value<bool>("keep_proxy"); if (o.ContainsKey("keep_proxy")) patch.KeepProxy = o.Value<bool>("keep_proxy");
if (o.ContainsKey("prefix") || o.ContainsKey("suffix") && !o.ContainsKey("proxy_tags")) if (o.ContainsKey("prefix") || o.ContainsKey("suffix") && !o.ContainsKey("proxy_tags"))
member.ProxyTags = new[] {new ProxyTag(o.Value<string>("prefix"), o.Value<string>("suffix"))}; patch.ProxyTags = new[] {new ProxyTag(o.Value<string>("prefix"), o.Value<string>("suffix"))};
else if (o.ContainsKey("proxy_tags")) else if (o.ContainsKey("proxy_tags"))
{ {
member.ProxyTags = o.Value<JArray>("proxy_tags") patch.ProxyTags = o.Value<JArray>("proxy_tags")
.OfType<JObject>().Select(o => new ProxyTag(o.Value<string>("prefix"), o.Value<string>("suffix"))) .OfType<JObject>().Select(o => new ProxyTag(o.Value<string>("prefix"), o.Value<string>("suffix")))
.ToList(); .ToArray();
} }
if(o.ContainsKey("privacy")) //TODO: Deprecate this completely in api v2 if(o.ContainsKey("privacy")) //TODO: Deprecate this completely in api v2
{ {
var plevel = o.Value<string>("privacy").ParsePrivacy("member"); var plevel = o.Value<string>("privacy").ParsePrivacy("member");
member.MemberVisibility = plevel; patch.Visibility = plevel;
member.NamePrivacy = plevel; patch.NamePrivacy = plevel;
member.AvatarPrivacy = plevel; patch.AvatarPrivacy = plevel;
member.DescriptionPrivacy = plevel; patch.DescriptionPrivacy = plevel;
member.BirthdayPrivacy = plevel; patch.BirthdayPrivacy = plevel;
member.PronounPrivacy = plevel; patch.PronounPrivacy = plevel;
// member.ColorPrivacy = plevel; // member.ColorPrivacy = plevel;
member.MetadataPrivacy = plevel; patch.MetadataPrivacy = plevel;
} }
else else
{ {
if (o.ContainsKey("visibility")) member.MemberVisibility = o.Value<string>("visibility").ParsePrivacy("member"); if (o.ContainsKey("visibility")) patch.Visibility = o.Value<string>("visibility").ParsePrivacy("member");
if (o.ContainsKey("name_privacy")) member.NamePrivacy = o.Value<string>("name_privacy").ParsePrivacy("member"); if (o.ContainsKey("name_privacy")) patch.NamePrivacy = o.Value<string>("name_privacy").ParsePrivacy("member");
if (o.ContainsKey("description_privacy")) member.DescriptionPrivacy = o.Value<string>("description_privacy").ParsePrivacy("member"); if (o.ContainsKey("description_privacy")) patch.DescriptionPrivacy = o.Value<string>("description_privacy").ParsePrivacy("member");
if (o.ContainsKey("avatar_privacy")) member.AvatarPrivacy = o.Value<string>("avatar_privacy").ParsePrivacy("member"); if (o.ContainsKey("avatar_privacy")) patch.AvatarPrivacy = o.Value<string>("avatar_privacy").ParsePrivacy("member");
if (o.ContainsKey("birthday_privacy")) member.BirthdayPrivacy = o.Value<string>("birthday_privacy").ParsePrivacy("member"); if (o.ContainsKey("birthday_privacy")) patch.BirthdayPrivacy = o.Value<string>("birthday_privacy").ParsePrivacy("member");
if (o.ContainsKey("pronoun_privacy")) member.PronounPrivacy = o.Value<string>("pronoun_privacy").ParsePrivacy("member"); if (o.ContainsKey("pronoun_privacy")) patch.PronounPrivacy = o.Value<string>("pronoun_privacy").ParsePrivacy("member");
// if (o.ContainsKey("color_privacy")) member.ColorPrivacy = o.Value<string>("color_privacy").ParsePrivacy("member"); // if (o.ContainsKey("color_privacy")) member.ColorPrivacy = o.Value<string>("color_privacy").ParsePrivacy("member");
if (o.ContainsKey("metadata_privacy")) member.MetadataPrivacy = o.Value<string>("metadata_privacy").ParsePrivacy("member"); if (o.ContainsKey("metadata_privacy")) patch.MetadataPrivacy = o.Value<string>("metadata_privacy").ParsePrivacy("member");
} }
return patch;
} }
private static string BoundsCheckField(this string input, int maxLength, string nameInError) private static string BoundsCheckField(this string input, int maxLength, string nameInError)

View File

@ -16,12 +16,14 @@ namespace PluralKit.API
public class MemberController: ControllerBase public class MemberController: ControllerBase
{ {
private IDataStore _data; private IDataStore _data;
private IDatabase _db;
private IAuthorizationService _auth; private IAuthorizationService _auth;
public MemberController(IDataStore data, IAuthorizationService auth) public MemberController(IDataStore data, IAuthorizationService auth, IDatabase db)
{ {
_data = data; _data = data;
_auth = auth; _auth = auth;
_db = db;
} }
[HttpGet("{hid}")] [HttpGet("{hid}")]
@ -48,18 +50,18 @@ namespace PluralKit.API
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 _data.CreateMember(system, properties.Value<string>("name"));
MemberPatch patch;
try try
{ {
member.ApplyJson(properties); patch = JsonModelExt.ToMemberPatch(properties);
} }
catch (JsonModelParseError e) catch (JsonModelParseError e)
{ {
return BadRequest(e.Message); return BadRequest(e.Message);
} }
// TODO: retire SaveMember var newMember = await _db.Execute(conn => conn.UpdateMember(member.Id, patch));
await _data.SaveMember(member); return Ok(member.ToJson(User.ContextFor(newMember)));
return Ok(member.ToJson(User.ContextFor(member)));
} }
[HttpPatch("{hid}")] [HttpPatch("{hid}")]
@ -72,18 +74,18 @@ namespace PluralKit.API
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.");
MemberPatch patch;
try try
{ {
member.ApplyJson(changes); patch = JsonModelExt.ToMemberPatch(changes);
} }
catch (JsonModelParseError e) catch (JsonModelParseError e)
{ {
return BadRequest(e.Message); return BadRequest(e.Message);
} }
// TODO: retire SaveMember var newMember = await _db.Execute(conn => conn.UpdateMember(member.Id, patch));
await _data.SaveMember(member); return Ok(member.ToJson(User.ContextFor(newMember)));
return Ok(member.ToJson(User.ContextFor(member)));
} }
[HttpDelete("{hid}")] [HttpDelete("{hid}")]

View File

@ -100,10 +100,10 @@ namespace PluralKit.Bot
var description = ctx.RemainderOrNull().NormalizeLineEndSpacing(); var description = ctx.RemainderOrNull().NormalizeLineEndSpacing();
if (description.IsLongerThan(Limits.MaxDescriptionLength)) if (description.IsLongerThan(Limits.MaxDescriptionLength))
throw Errors.DescriptionTooLongError(description.Length); throw Errors.DescriptionTooLongError(description.Length);
target.Description = description;
var patch = new MemberPatch {Description = Partial<string>.Present(description)}; var patch = new MemberPatch {Description = Partial<string>.Present(description)};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch)); await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member description changed."); await ctx.Reply($"{Emojis.Success} Member description changed.");
} }
} }

View File

@ -56,8 +56,6 @@ namespace PluralKit.Bot
throw Errors.GenericCancelled(); throw Errors.GenericCancelled();
} }
target.ProxyTags = new ProxyTag[] { };
var patch = new MemberPatch {ProxyTags = Partial<ProxyTag[]>.Present(new ProxyTag[0])}; var patch = new MemberPatch {ProxyTags = Partial<ProxyTag[]>.Present(new ProxyTag[0])};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch)); await _db.Execute(conn => conn.UpdateMember(target.Id, patch));

View File

@ -9,27 +9,27 @@ namespace PluralKit.Core {
public class PKMember public class PKMember
{ {
public MemberId Id { get; } public MemberId Id { get; }
public string Hid { get; set; } public string Hid { get; }
public SystemId System { get; set; } public SystemId System { get; }
public string Color { get; set; } public string Color { get; }
public string AvatarUrl { get; set; } public string AvatarUrl { get; }
public string Name { get; set; } public string Name { get; }
public string DisplayName { get; set; } public string DisplayName { get; }
public LocalDate? Birthday { get; set; } public LocalDate? Birthday { get; }
public string Pronouns { get; set; } public string Pronouns { get; }
public string Description { get; set; } public string Description { get; }
public ICollection<ProxyTag> ProxyTags { get; set; } public ICollection<ProxyTag> ProxyTags { get; }
public bool KeepProxy { get; set; } public bool KeepProxy { get; }
public Instant Created { get; set; } public Instant Created { get; }
public int MessageCount { get; set; } public int MessageCount { get; }
public PrivacyLevel MemberVisibility { get; set; } public PrivacyLevel MemberVisibility { get; }
public PrivacyLevel DescriptionPrivacy { get; set; } public PrivacyLevel DescriptionPrivacy { get; }
public PrivacyLevel AvatarPrivacy { get; set; } public PrivacyLevel AvatarPrivacy { get; }
public PrivacyLevel NamePrivacy { get; set; } //ignore setting if no display name is set public PrivacyLevel NamePrivacy { get; } //ignore setting if no display name is set
public PrivacyLevel BirthdayPrivacy { get; set; } public PrivacyLevel BirthdayPrivacy { get; }
public PrivacyLevel PronounPrivacy { get; set; } public PrivacyLevel PronounPrivacy { get; }
public PrivacyLevel MetadataPrivacy { get; set; } public PrivacyLevel MetadataPrivacy { get; }
// public PrivacyLevel ColorPrivacy { get; set; } // public PrivacyLevel ColorPrivacy { get; set; }
/// Returns a formatted string representing the member's birthday, taking into account that a year of "0001" or "0004" is hidden /// Returns a formatted string representing the member's birthday, taking into account that a year of "0001" or "0004" is hidden

View File

@ -8,6 +8,7 @@ namespace PluralKit.Core
{ {
public Partial<string> Name { get; set; } public Partial<string> Name { get; set; }
public Partial<string?> DisplayName { get; set; } public Partial<string?> DisplayName { get; set; }
public Partial<string?> AvatarUrl { get; set; }
public Partial<string?> Color { get; set; } public Partial<string?> Color { get; set; }
public Partial<LocalDate?> Birthday { get; set; } public Partial<LocalDate?> Birthday { get; set; }
public Partial<string?> Pronouns { get; set; } public Partial<string?> Pronouns { get; set; }
@ -26,6 +27,7 @@ namespace PluralKit.Core
public override UpdateQueryBuilder Apply(UpdateQueryBuilder b) => b public override UpdateQueryBuilder Apply(UpdateQueryBuilder b) => b
.With("name", Name) .With("name", Name)
.With("display_name", DisplayName) .With("display_name", DisplayName)
.With("avatar_url", AvatarUrl)
.With("color", Color) .With("color", Color)
.With("birthday", Birthday) .With("birthday", Birthday)
.With("pronouns", Pronouns) .With("pronouns", Pronouns)

View File

@ -72,12 +72,10 @@ namespace PluralKit.Core
}; };
} }
private PKMember ConvertMember(PKSystem system, DataFileMember fileMember) private MemberPatch ToMemberPatch(DataFileMember fileMember)
{ {
var newMember = new PKMember var newMember = new MemberPatch
{ {
Hid = fileMember.Id,
System = system.Id,
Name = fileMember.Name, Name = fileMember.Name,
DisplayName = fileMember.DisplayName, DisplayName = fileMember.DisplayName,
Description = fileMember.Description, Description = fileMember.Description,
@ -88,10 +86,10 @@ namespace PluralKit.Core
}; };
if (fileMember.Prefix != null || fileMember.Suffix != null) if (fileMember.Prefix != null || fileMember.Suffix != null)
newMember.ProxyTags = new List<ProxyTag> {new ProxyTag(fileMember.Prefix, fileMember.Suffix)}; newMember.ProxyTags = new[] {new ProxyTag(fileMember.Prefix, fileMember.Suffix)};
else else
// Ignore proxy tags where both prefix and suffix are set to null (would be invalid anyway) // Ignore proxy tags where both prefix and suffix are set to null (would be invalid anyway)
newMember.ProxyTags = (fileMember.ProxyTags ?? new ProxyTag[] { }).Where(tag => !tag.IsEmpty).ToList(); newMember.ProxyTags = (fileMember.ProxyTags ?? new ProxyTag[] { }).Where(tag => !tag.IsEmpty).ToArray();
if (fileMember.Birthday != null) if (fileMember.Birthday != null)
{ {
@ -149,7 +147,7 @@ namespace PluralKit.Core
_logger.Debug( _logger.Debug(
"Importing member with identifier {FileId} to system {System} (is creating new member? {IsCreatingNewMember})", "Importing member with identifier {FileId} to system {System} (is creating new member? {IsCreatingNewMember})",
fileMember.Id, system.Id, isCreatingNewMember); fileMember.Id, system.Id, isCreatingNewMember);
var newMember = await imp.AddMember(fileMember.Id, ConvertMember(system, fileMember)); var newMember = await imp.AddMember(fileMember.Id, fileMember.Id, fileMember.Name, ToMemberPatch(fileMember));
if (isCreatingNewMember) if (isCreatingNewMember)
result.AddedNames.Add(newMember.Name); result.AddedNames.Add(newMember.Name);

View File

@ -60,43 +60,45 @@ namespace PluralKit.Core
/// </summary> /// </summary>
/// <remarks>If an existing member exists in this system that matches this member in either HID or name, it'll overlay the member information on top of this instead.</remarks> /// <remarks>If an existing member exists in this system that matches this member in either HID or name, it'll overlay the member information on top of this instead.</remarks>
/// <param name="identifier">An opaque identifier string that refers to this member regardless of source. Is used when importing switches. Value is irrelevant, but should be consistent with the same member later.</param> /// <param name="identifier">An opaque identifier string that refers to this member regardless of source. Is used when importing switches. Value is irrelevant, but should be consistent with the same member later.</param>
/// <param name="member">A member struct containing the data to apply to this member. Null fields will be ignored.</param> /// <param name="potentialHid">When trying to match the member to an existing member, will use a member with this HID if present in system.</param>
/// <param name="potentialName">When trying to match the member to an existing member, will use a member with this name if present in system.</param>
/// <param name="patch">A member patch struct containing the data to apply to this member </param>
/// <returns>The inserted member object, which may or may not share an ID or HID with the input member.</returns> /// <returns>The inserted member object, which may or may not share an ID or HID with the input member.</returns>
public async Task<PKMember> AddMember(string identifier, PKMember member) public async Task<PKMember> AddMember(string identifier, string potentialHid, string potentialName, MemberPatch patch)
{ {
// See if we can find a member that matches this one // See if we can find a member that matches this one
// if not, roll a new hid and we'll insert one with that // if not, roll a new hid and we'll insert one with that
// (we can't trust the hid given in the member, it might let us overwrite another system's members) // (we can't trust the hid given in the member, it might let us overwrite another system's members)
var existingMember = FindExistingMemberInSystem(member.Hid, member.Name); var existingMember = FindExistingMemberInSystem(potentialHid, potentialName);
string newHid = existingMember?.Hid ?? await _conn.QuerySingleAsync<string>("find_free_member_hid", commandType: CommandType.StoredProcedure); string newHid = existingMember?.Hid ?? await _conn.QuerySingleAsync<string>("find_free_member_hid", commandType: CommandType.StoredProcedure);
// Upsert member data and return the ID // Upsert member data and return the ID
QueryBuilder qb = QueryBuilder.Upsert("members", "hid") QueryBuilder qb = QueryBuilder.Upsert("members", "hid")
.Constant("hid", "@Hid") .Constant("hid", "@Hid")
.Constant("system", "@System") .Constant("system", "@System");
.Variable("name", "@Name")
.Variable("keep_proxy", "@KeepProxy");
if (member.DisplayName != null) qb.Variable("display_name", "@DisplayName"); if (patch.Name.IsPresent) qb.Variable("name", "@Name");
if (member.Description != null) qb.Variable("description", "@Description"); if (patch.DisplayName.IsPresent) qb.Variable("display_name", "@DisplayName");
if (member.Color != null) qb.Variable("color", "@Color"); if (patch.Description.IsPresent) qb.Variable("description", "@Description");
if (member.AvatarUrl != null) qb.Variable("avatar_url", "@AvatarUrl"); if (patch.Color.IsPresent) qb.Variable("color", "@Color");
if (member.ProxyTags != null) qb.Variable("proxy_tags", "@ProxyTags"); if (patch.AvatarUrl.IsPresent) qb.Variable("avatar_url", "@AvatarUrl");
if (member.Birthday != null) qb.Variable("birthday", "@Birthday"); if (patch.ProxyTags.IsPresent) qb.Variable("proxy_tags", "@ProxyTags");
if (patch.Birthday.IsPresent) qb.Variable("birthday", "@Birthday");
if (patch.KeepProxy.IsPresent) qb.Variable("keep_proxy", "@KeepProxy");
var newMember = await _conn.QueryFirstAsync<PKMember>(qb.Build("returning *"), var newMember = await _conn.QueryFirstAsync<PKMember>(qb.Build("returning *"),
new new
{ {
Hid = newHid, Hid = newHid,
System = _systemId, System = _systemId,
member.Name, Name = patch.Name.Value,
member.DisplayName, DisplayName = patch.DisplayName.Value,
member.Description, Description = patch.Description.Value,
member.Color, Color = patch.Color.Value,
member.AvatarUrl, AvatarUrl = patch.AvatarUrl.Value,
member.KeepProxy, KeepProxy = patch.KeepProxy.Value,
member.ProxyTags, ProxyTags = patch.ProxyTags.Value,
member.Birthday Birthday = patch.Birthday.Value
}); });
// Log this member ID by the given identifier // Log this member ID by the given identifier

View File

@ -30,6 +30,8 @@ namespace PluralKit.Core
public IEnumerator<T> GetEnumerator() => ToArray().GetEnumerator(); public IEnumerator<T> GetEnumerator() => ToArray().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => ToArray().GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => ToArray().GetEnumerator();
public static implicit operator Partial<T>(T val) => Present(val);
} }
public class PartialConverter: JsonConverter public class PartialConverter: JsonConverter