Skip to content

Commit

Permalink
fix: naming convention
Browse files Browse the repository at this point in the history
fix: make ObservableApiObject protected
fix: private properties
fix: missing json ignore
  • Loading branch information
Lulalaby committed Jul 27, 2023
1 parent c69622e commit f591d52
Show file tree
Hide file tree
Showing 25 changed files with 113 additions and 89 deletions.
12 changes: 6 additions & 6 deletions DisCatSharp.ApplicationCommands/ApplicationCommandsExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -879,8 +879,8 @@ private async void CheckRegistrationStartup(bool man = false, List<CommandTransl
{
if (translation != null && translation.Any())
{
var file_name = $"translation_generator_export-shard{this.Client.ShardId}-SINGLE-{s_registrationCount}_of_{s_expectedCount}.json";
var fs = File.Create(file_name);
var fileName = $"translation_generator_export-shard{this.Client.ShardId}-SINGLE-{s_registrationCount}_of_{s_expectedCount}.json";
var fs = File.Create(fileName);
var ms = new MemoryStream();
var writer = new StreamWriter(ms);
await writer.WriteAsync(JsonConvert.SerializeObject(translation.DistinctBy(x => x.Name), Formatting.Indented)).ConfigureAwait(false);
Expand All @@ -892,13 +892,13 @@ private async void CheckRegistrationStartup(bool man = false, List<CommandTransl
await fs.DisposeAsync().ConfigureAwait(false);
ms.Close();
await ms.DisposeAsync().ConfigureAwait(false);
this.Client.Logger.LogInformation("Exported base translation to {exppath}", file_name);
this.Client.Logger.LogInformation("Exported base translation to {exppath}", fileName);
}

if (groupTranslation != null && groupTranslation.Any())
{
var file_name = $"translation_generator_export-shard{this.Client.ShardId}-GROUP-{s_registrationCount}_of_{s_expectedCount}.json";
var fs = File.Create(file_name);
var fileName = $"translation_generator_export-shard{this.Client.ShardId}-GROUP-{s_registrationCount}_of_{s_expectedCount}.json";
var fs = File.Create(fileName);
var ms = new MemoryStream();
var writer = new StreamWriter(ms);
await writer.WriteAsync(JsonConvert.SerializeObject(groupTranslation.DistinctBy(x => x.Name), Formatting.Indented)).ConfigureAwait(false);
Expand All @@ -910,7 +910,7 @@ private async void CheckRegistrationStartup(bool man = false, List<CommandTransl
await fs.DisposeAsync().ConfigureAwait(false);
ms.Close();
await ms.DisposeAsync().ConfigureAwait(false);
this.Client.Logger.LogInformation("Exported base translation to {exppath}", file_name);
this.Client.Logger.LogInformation("Exported base translation to {exppath}", fileName);
}
}
catch (Exception ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public sealed class ContextMenuCooldownAttribute : ApplicationCommandCheckBaseAt
/// <summary>
/// Gets the cooldown buckets for this command.
/// </summary>
internal readonly ConcurrentDictionary<string, ContextMenuCooldownBucket> _buckets;
internal readonly ConcurrentDictionary<string, ContextMenuCooldownBucket> Buckets;

/// <summary>
/// Defines a cooldown for this command. This means that users will be able to use the command a specific number of times before they have to wait to use it again.
Expand All @@ -67,7 +67,7 @@ public ContextMenuCooldownAttribute(int maxUses, double resetAfter, CooldownBuck
this.MaxUses = maxUses;
this.Reset = TimeSpan.FromSeconds(resetAfter);
this.BucketType = bucketType;
this._buckets = new ConcurrentDictionary<string, ContextMenuCooldownBucket>();
this.Buckets = new ConcurrentDictionary<string, ContextMenuCooldownBucket>();
}

/// <summary>
Expand All @@ -78,7 +78,7 @@ public ContextMenuCooldownAttribute(int maxUses, double resetAfter, CooldownBuck
public ContextMenuCooldownBucket GetBucket(BaseContext ctx)
{
var bid = this.GetBucketId(ctx, out _, out _, out _);
this._buckets.TryGetValue(bid, out var bucket);
this.Buckets.TryGetValue(bid, out var bucket);
return bucket;
}

Expand Down Expand Up @@ -128,10 +128,10 @@ private string GetBucketId(BaseContext ctx, out ulong userId, out ulong channelI
public override async Task<bool> ExecuteChecksAsync(BaseContext ctx)
{
var bid = this.GetBucketId(ctx, out var usr, out var chn, out var gld);
if (!this._buckets.TryGetValue(bid, out var bucket))
if (!this.Buckets.TryGetValue(bid, out var bucket))
{
bucket = new ContextMenuCooldownBucket(this.MaxUses, this.Reset, usr, chn, gld);
this._buckets.AddOrUpdate(bid, bucket, (k, v) => bucket);
this.Buckets.AddOrUpdate(bid, bucket, (k, v) => bucket);
}

return await bucket.DecrementUseAsync().ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public sealed class SlashCommandCooldownAttribute : ApplicationCommandCheckBaseA
/// <summary>
/// Gets the cooldown buckets for this command.
/// </summary>
internal readonly ConcurrentDictionary<string, SlashCommandCooldownBucket> _buckets;
internal readonly ConcurrentDictionary<string, SlashCommandCooldownBucket> Buckets;

/// <summary>
/// Defines a cooldown for this command. This means that users will be able to use the command a specific number of times before they have to wait to use it again.
Expand All @@ -67,7 +67,7 @@ public SlashCommandCooldownAttribute(int maxUses, double resetAfter, CooldownBuc
this.MaxUses = maxUses;
this.Reset = TimeSpan.FromSeconds(resetAfter);
this.BucketType = bucketType;
this._buckets = new ConcurrentDictionary<string, SlashCommandCooldownBucket>();
this.Buckets = new ConcurrentDictionary<string, SlashCommandCooldownBucket>();
}

/// <summary>
Expand All @@ -78,7 +78,7 @@ public SlashCommandCooldownAttribute(int maxUses, double resetAfter, CooldownBuc
public SlashCommandCooldownBucket GetBucket(BaseContext ctx)
{
var bid = this.GetBucketId(ctx, out _, out _, out _);
this._buckets.TryGetValue(bid, out var bucket);
this.Buckets.TryGetValue(bid, out var bucket);
return bucket;
}

Expand Down Expand Up @@ -128,10 +128,10 @@ private string GetBucketId(BaseContext ctx, out ulong userId, out ulong channelI
public override async Task<bool> ExecuteChecksAsync(BaseContext ctx)
{
var bid = this.GetBucketId(ctx, out var usr, out var chn, out var gld);
if (!this._buckets.TryGetValue(bid, out var bucket))
if (!this.Buckets.TryGetValue(bid, out var bucket))
{
bucket = new SlashCommandCooldownBucket(this.MaxUses, this.Reset, usr, chn, gld);
this._buckets.AddOrUpdate(bid, bucket, (k, v) => bucket);
this.Buckets.AddOrUpdate(bid, bucket, (k, v) => bucket);
}

return await bucket.DecrementUseAsync().ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ internal static class ApplicationCommandEqualityChecks
/// <param name="ac1">Source command.</param>
/// <param name="targetApplicationCommand">Command to check against.</param>
/// <param name="client">The discord client.</param>
/// <param name="IsGuild">Whether the equal check is performed for a guild command.</param>
internal static bool IsEqualTo(this DiscordApplicationCommand ac1, DiscordApplicationCommand targetApplicationCommand, DiscordClient client, bool IsGuild)
/// <param name="isGuild">Whether the equal check is performed for a guild command.</param>
internal static bool IsEqualTo(this DiscordApplicationCommand ac1, DiscordApplicationCommand targetApplicationCommand, DiscordClient client, bool isGuild)
{
if (targetApplicationCommand is null || ac1 is null)
return false;
Expand All @@ -56,15 +56,15 @@ internal static bool IsEqualTo(this DiscordApplicationCommand ac1, DiscordApplic
if (sourceApplicationCommand.DefaultMemberPermissions == Permissions.None && targetApplicationCommand.DefaultMemberPermissions == null)
sourceApplicationCommand.DefaultMemberPermissions = null;

if (IsGuild)
if (isGuild)
{
sourceApplicationCommand.DmPermission = null;
targetApplicationCommand.DmPermission = null;
}

client.Logger.Log(ApplicationCommandsExtension.ApplicationCommandsLogLevel, "[AC Change Check] Command {name}\n\n[{jsonOne},{jsontwo}]\n\n", ac1.Name, JsonConvert.SerializeObject(sourceApplicationCommand), JsonConvert.SerializeObject(targetApplicationCommand));

return ac1.Type == targetApplicationCommand.Type && sourceApplicationCommand.SoftEqual(targetApplicationCommand, ac1.Type, ApplicationCommandsExtension.Configuration?.EnableLocalization ?? false, IsGuild);
return ac1.Type == targetApplicationCommand.Type && sourceApplicationCommand.SoftEqual(targetApplicationCommand, ac1.Type, ApplicationCommandsExtension.Configuration?.EnableLocalization ?? false, isGuild);
}

/// <summary>
Expand Down
18 changes: 9 additions & 9 deletions DisCatSharp.ApplicationCommands/Entities/CooldownBucket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public class CooldownBucket : IBucket, IEquatable<CooldownBucket>
/// <summary>
/// The remaining uses for this bucket.
/// </summary>
public int RemainingUses => Volatile.Read(ref this._remainingUses);
public int RemainingUses => Volatile.Read(ref this.RemainingUsesInternal);

/// <summary>
/// The max uses for this bucket.
Expand All @@ -72,9 +72,9 @@ public class CooldownBucket : IBucket, IEquatable<CooldownBucket>
/// <summary>
/// Gets the semaphore used to lock the use value.
/// </summary>
internal readonly SemaphoreSlim _usageSemaphore;
internal readonly SemaphoreSlim UsageSemaphore;

internal int _remainingUses;
internal int RemainingUsesInternal;

/// <summary>
/// Creates a new command cooldown bucket.
Expand All @@ -86,15 +86,15 @@ public class CooldownBucket : IBucket, IEquatable<CooldownBucket>
/// <param name="guildId">ID of the guild with which this cooldown is associated.</param>
internal CooldownBucket(int maxUses, TimeSpan resetAfter, ulong userId = 0, ulong channelId = 0, ulong guildId = 0)
{
this._remainingUses = maxUses;
this.RemainingUsesInternal = maxUses;
this.MaxUses = maxUses;
this.ResetsAt = DateTimeOffset.UtcNow + resetAfter;
this.Reset = resetAfter;
this.UserId = userId;
this.ChannelId = channelId;
this.GuildId = guildId;
this.BucketId = MakeId(userId, channelId, guildId);
this._usageSemaphore = new(1, 1);
this.UsageSemaphore = new(1, 1);
}

/// <summary>
Expand All @@ -103,15 +103,15 @@ internal CooldownBucket(int maxUses, TimeSpan resetAfter, ulong userId = 0, ulon
/// <returns>Whether decrement succeeded or not.</returns>
internal async Task<bool> DecrementUseAsync()
{
await this._usageSemaphore.WaitAsync().ConfigureAwait(false);
await this.UsageSemaphore.WaitAsync().ConfigureAwait(false);
Console.WriteLine($"[DecrementUseAsync]: Remaining: {this.RemainingUses}/{this.MaxUses} Resets: {this.ResetsAt} Now: {DateTimeOffset.UtcNow} Vars[u,c,g]: {this.UserId} {this.ChannelId} {this.GuildId} Id: {this.BucketId}");

// if we're past reset time...
var now = DateTimeOffset.UtcNow;
if (now >= this.ResetsAt)
{
// ...do the reset and set a new reset time
Interlocked.Exchange(ref this._remainingUses, this.MaxUses);
Interlocked.Exchange(ref this.RemainingUsesInternal, this.MaxUses);
this.ResetsAt = now + this.Reset;
}

Expand All @@ -120,12 +120,12 @@ internal async Task<bool> DecrementUseAsync()
if (this.RemainingUses > 0)
{
// ...decrement, and return success...
Interlocked.Decrement(ref this._remainingUses);
Interlocked.Decrement(ref this.RemainingUsesInternal);
success = true;
}
Console.WriteLine($"[DecrementUseAsync]: Remaining: {this.RemainingUses}/{this.MaxUses} Resets: {this.ResetsAt} Now: {DateTimeOffset.UtcNow} Vars[u,c,g]: {this.UserId} {this.ChannelId} {this.GuildId} Id: {this.BucketId}");
// ...otherwise just fail
this._usageSemaphore.Release();
this.UsageSemaphore.Release();
return success;
}

Expand Down
6 changes: 3 additions & 3 deletions DisCatSharp.Lavalink/Entities/LavalinkTrack.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,16 @@ public sealed class LavalinkPluginInfo
/// Gets additional json properties that are not known to the deserializing object.
/// </summary>
[JsonIgnore]
internal IDictionary<string, object> _unknownProperties = new Dictionary<string, object>();
internal IDictionary<string, object> UnknownProperties = new Dictionary<string, object>();

/// <summary>
/// Lets JsonConvert set the unknown properties.
/// </summary>
[JsonExtensionData(ReadData = true, WriteData = false)]
public IDictionary<string, object> AdditionalProperties
{
get => this._unknownProperties;
set => this._unknownProperties = value;
get => this.UnknownProperties;
set => this.UnknownProperties = value;
}
}

Expand Down
8 changes: 4 additions & 4 deletions DisCatSharp/Clients/DiscordClient.Events.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1052,12 +1052,12 @@ internal void EventErrorHandler<TSender, TArgs>(AsyncEvent<TSender, TArgs> async
/// </summary>
public event AsyncEventHandler<DiscordClient, RateLimitExceptionEventArgs> RateLimitHit
{
add => this._rateLimitHit.Register(value);
remove => this._rateLimitHit.Unregister(value);
add => this.RateLimitHitInternal.Register(value);
remove => this.RateLimitHitInternal.Unregister(value);
}
internal AsyncEvent<DiscordClient, RateLimitExceptionEventArgs> _rateLimitHit;
internal AsyncEvent<DiscordClient, RateLimitExceptionEventArgs> RateLimitHitInternal;

/// <summary>
/// <summary>
/// Fired on heartbeat attempt cancellation due to too many failed heartbeats.
/// </summary>
public event AsyncEventHandler<DiscordClient, ZombiedEventArgs> Zombied
Expand Down
2 changes: 1 addition & 1 deletion DisCatSharp/Clients/DiscordClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ internal void InternalSetup()
this._guildMemberTimeoutAdded = new("GUILD_MEMBER_TIMEOUT_ADDED", EventExecutionLimit, this.EventErrorHandler);
this._guildMemberTimeoutChanged = new("GUILD_MEMBER_TIMEOUT_UPDATED", EventExecutionLimit, this.EventErrorHandler);
this._guildMemberTimeoutRemoved = new("GUILD_MEMBER_TIMEOUT_REMOVED", EventExecutionLimit, this.EventErrorHandler);
this._rateLimitHit = new("RATELIMIT_HIT", EventExecutionLimit, this.EventErrorHandler);
this.RateLimitHitInternal = new("RATELIMIT_HIT", EventExecutionLimit, this.EventErrorHandler);
this._automodRuleCreated = new("AUTO_MODERATION_RULE_CREATED", EventExecutionLimit, this.EventErrorHandler);
this._automodRuleUpdated = new("AUTO_MODERATION_RULE_UPDATED", EventExecutionLimit, this.EventErrorHandler);
this._automodRuleDeleted = new("AUTO_MODERATION_RULE_DELETED", EventExecutionLimit, this.EventErrorHandler);
Expand Down
4 changes: 2 additions & 2 deletions DisCatSharp/DiscordConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,11 +235,11 @@ public bool UseCanary
[Deprecated("Use ApiChannel instead.")]
public bool UsePtb
{
internal get => this.ApiChannel == ApiChannel.PTB;
internal get => this.ApiChannel == ApiChannel.Ptb;
set
{
if (value)
this.ApiChannel = ApiChannel.PTB;
this.ApiChannel = ApiChannel.Ptb;
}
}

Expand Down
8 changes: 4 additions & 4 deletions DisCatSharp/Entities/Guild/DiscordGuild.AuditLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -433,18 +433,18 @@ PropertyChange<DiscordChannel> GetChannelChange()
};
break;
case "available_tags":
var old_tags = xc.OldValues?.OfType<JObject>()
var oldTags = xc.OldValues?.OfType<JObject>()
?.Select(xjo => xjo.ToObject<ForumPostTag>())
?.Select(xo => { xo.Discord = this.Discord; return xo; });

var new_tags = xc.NewValues?.OfType<JObject>()
var newTags = xc.NewValues?.OfType<JObject>()
?.Select(xjo => xjo.ToObject<ForumPostTag>())
?.Select(xo => { xo.Discord = this.Discord; return xo; });

entrychn.AvailableTagsChange = new()
{
Before = old_tags != null ? new List<ForumPostTag>(new List<ForumPostTag>(old_tags)) : null,
After = new_tags != null ? new List<ForumPostTag>(new List<ForumPostTag>(new_tags)) : null
Before = oldTags != null ? new List<ForumPostTag>(new List<ForumPostTag>(oldTags)) : null,
After = newTags != null ? new List<ForumPostTag>(new List<ForumPostTag>(newTags)) : null
};
break;

Expand Down
4 changes: 2 additions & 2 deletions DisCatSharp/Entities/Guild/DiscordGuild.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2001,7 +2001,7 @@ public Task<DiscordSticker> CreateStickerAsync(string name, string description,
{
StickerFormat.Png => "png",
StickerFormat.Apng => "png",
StickerFormat.GIF => "gif",
StickerFormat.Gif => "gif",
StickerFormat.Lottie => "json",
_ => throw new InvalidOperationException("This format is not supported.")
};
Expand All @@ -2010,7 +2010,7 @@ public Task<DiscordSticker> CreateStickerAsync(string name, string description,
{
StickerFormat.Png => "image/png",
StickerFormat.Apng => "image/png",
StickerFormat.GIF => "image/gif",
StickerFormat.Gif => "image/gif",
StickerFormat.Lottie => "application/json",
_ => throw new InvalidOperationException("This format is not supported.")
};
Expand Down
10 changes: 7 additions & 3 deletions DisCatSharp/Entities/Guild/DiscordRole.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,23 +122,25 @@ public string IconUrl
/// <summary>
/// Gets the unicode emoji.
/// </summary>
[JsonIgnore]
public DiscordEmoji UnicodeEmoji
=> this.UnicodeEmojiString != null ? DiscordEmoji.FromName(this.Discord, $":{this.UnicodeEmojiString}:", false) : null;

/// <summary>
/// Gets the guild this role belongs to.
/// </summary>
[JsonIgnore]
public DiscordGuild Guild
{
get
{
this._guild ??= this.Discord.Guilds[this.GuildId];
return this._guild;
this.GuildInternal ??= this.Discord.Guilds[this.GuildId];
return this.GuildInternal;
}
}

[JsonIgnore]
internal DiscordGuild _guild { get; set; }
internal DiscordGuild GuildInternal { get; set; }

[JsonIgnore]
internal ulong GuildId = 0;
Expand All @@ -152,12 +154,14 @@ public DiscordGuild Guild
/// <summary>
/// Gets a mention string for this role. If the role is mentionable, this string will mention all the users that belong to this role.
/// </summary>
[JsonIgnore]
public string Mention
=> Formatter.Mention(this);

/// <summary>
/// Gets a list of members that have this role. Requires ServerMembers Intent.
/// </summary>
[JsonIgnore]
public IReadOnlyList<KeyValuePair<ulong, DiscordMember>> Members
=> this.Guild.Members.Where(x => x.Value.RoleIds.Any(x => x == this.Id)).ToList();

Expand Down
Loading

0 comments on commit f591d52

Please sign in to comment.