Skip to content

Commit

Permalink
chore: some improvemnts in code quality, speed and readability
Browse files Browse the repository at this point in the history
  • Loading branch information
Lulalaby committed Dec 25, 2023
1 parent bc5401a commit 06db7b0
Show file tree
Hide file tree
Showing 41 changed files with 747 additions and 463 deletions.
10 changes: 0 additions & 10 deletions DisCatSharp/DisCatSharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,6 @@

</PropertyGroup>

<ItemGroup>
<None Remove="res\discatsharp.png" />
</ItemGroup>

<ItemGroup>
<Content Include="res\discatsharp.png">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Content>
</ItemGroup>

<ItemGroup>
<PackageReference Include="DisCatSharp.Analyzer.Roselyn" Version="6.2.2">
<PrivateAssets>all</PrivateAssets>
Expand Down
8 changes: 4 additions & 4 deletions DisCatSharp/DiscordConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public string? Token

/// <summary>
/// <para>Sets the minimum logging level for messages.</para>
/// <para>Typically, the default value of <see cref="LogLevel.Information"/> is ok for most uses.</para>
/// <para>Defaults to <see cref="LogLevel.Information"/>.</para>
/// </summary>
public LogLevel MinimumLogLevel { internal get; set; } = LogLevel.Information;

Expand Down Expand Up @@ -114,7 +114,7 @@ public string? Token
/// <para>Sets the proxy to use for HTTP and WebSocket connections to Discord.</para>
/// <para>Defaults to <see langword="null"/>.</para>
/// </summary>
public IWebProxy Proxy { internal get; set; } = null!;
public IWebProxy? Proxy { internal get; set; } = null;

/// <summary>
/// <para>Sets the timeout for HTTP requests.</para>
Expand Down Expand Up @@ -213,7 +213,7 @@ public UdpClientFactoryDelegate UdpClientFactory
/// <para>Do not use, this is meant for DisCatSharp Devs.</para>
/// <para>Defaults to <see langword="null"/>.</para>
/// </summary>
public string Override { internal get; set; } = null!;
public string? Override { internal get; set; } = null;

/// <summary>
/// Sets your preferred API language. See <see cref="DiscordLocales" /> for valid locales.
Expand All @@ -237,7 +237,7 @@ public UdpClientFactoryDelegate UdpClientFactory
/// <para>This allows passing data around without resorting to static members.</para>
/// <para>Defaults to an empty service provider.</para>
/// </summary>
public IServiceProvider ServiceProvider { internal get; set; } = new ServiceCollection().BuildServiceProvider(true);
public IServiceProvider ServiceProvider { internal get; init; } = new ServiceCollection().BuildServiceProvider(true);

/// <summary>
/// <para>Whether to report missing fields for discord object.</para>
Expand Down
25 changes: 8 additions & 17 deletions DisCatSharp/Entities/Message/DiscordMessageFile.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
using System.IO;

using DisCatSharp.Attributes;

namespace DisCatSharp.Entities;

/// <summary>
/// Represents the File that should be sent to Discord from the <see cref="DisCatSharp.Entities.DiscordMessageBuilder"/>.
/// </summary>
public class DiscordMessageFile
public sealed class DiscordMessageFile
{
/// <summary>
/// Initializes a new instance of the <see cref="DiscordMessageFile"/> class.
Expand All @@ -18,7 +16,7 @@ public class DiscordMessageFile
/// <param name="fileType">The file type.</param>
/// <param name="contentType">The content type.</param>
/// <param name="description">The description.</param>
internal DiscordMessageFile(string filename, Stream stream, long? resetPositionTo, string fileType = null, string contentType = null, string description = null)
internal DiscordMessageFile(string filename, Stream stream, long? resetPositionTo, string? fileType = null, string? contentType = null, string? description = null)
{
this.Filename = filename;
this.FileType = fileType;
Expand All @@ -31,37 +29,30 @@ internal DiscordMessageFile(string filename, Stream stream, long? resetPositionT
/// <summary>
/// Gets the name of the File.
/// </summary>
public string Filename { get; internal set; }

/// <summary>
/// Gets the FileName of the File. Please use <see cref="Filename"/> in future.
/// </summary>
[Deprecated("Naming was incorrect, will be removed in future in favor of Filename")]
public string FileName
=> this.Filename;
public string Filename { get; }

/// <summary>
/// Gets the description of the File.
/// </summary>
public string Description { get; internal set; }
public string? Description { get; }

/// <summary>
/// Gets the stream of the File.
/// </summary>
public Stream Stream { get; internal set; }
public Stream Stream { get; }

/// <summary>
/// Gets or sets the file type.
/// </summary>
internal string FileType { get; set; }
internal string? FileType { get; }

/// <summary>
/// Gets or sets the content type.
/// </summary>
internal string ContentType { get; set; }
internal string? ContentType { get; }

/// <summary>
/// Gets the position the File should be reset to.
/// </summary>
internal long? ResetPositionTo { get; set; }
internal long? ResetPositionTo { get; }
}
4 changes: 2 additions & 2 deletions DisCatSharp/Entities/User/DiscordPresence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,15 @@ public DiscordGuild Guild
/// </summary>
// TODO: Add broadcast field
internal DiscordPresence()
: base(["broadcast"])
: base(["broadcast", "roles", "premium_since", "nick", "game"])
{ }

/// <summary>
/// Initializes a new instance of the <see cref="DiscordPresence"/> class.
/// </summary>
/// <param name="other">The other.</param>
internal DiscordPresence(DiscordPresence other)
: base(["broadcast"])
: base(["broadcast", "roles", "premium_since", "nick", "game"])
{
this.Discord = other.Discord;
this.Activity = other.Activity;
Expand Down
18 changes: 9 additions & 9 deletions DisCatSharp/Exceptions/BadRequestException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,17 @@ public class BadRequestException : DisCatSharpException
/// <summary>
/// Gets the error code for this exception.
/// </summary>
public int Code { get; internal set; }
public int? Code { get; internal set; } = null;

/// <summary>
/// Gets the JSON message received.
/// </summary>
public string JsonMessage { get; internal set; }
public string? JsonMessage { get; internal set; } = null;

/// <summary>
/// Gets the form error responses in JSON format.
/// </summary>
public string Errors { get; internal set; }
public string? Errors { get; internal set; } = null;

/// <summary>
/// Initializes a new instance of the <see cref="BadRequestException"/> class.
Expand All @@ -49,14 +49,14 @@ internal BadRequestException(BaseRestRequest request, RestResponse response)
{
var j = JObject.Parse(response.Response);

if (j["code"] != null)
this.Code = (int)j["code"];
if (j["code"] is not null)
this.Code = (int)j["code"]!;

if (j["message"] != null)
this.JsonMessage = j["message"].ToString();
if (j["message"] is not null)
this.JsonMessage = j["message"]!.ToString();

if (j["errors"] != null)
this.Errors = j["errors"].ToString();
if (j["errors"] is not null)
this.Errors = j["errors"]!.ToString();
}
catch
{ }
Expand Down
7 changes: 7 additions & 0 deletions DisCatSharp/Exceptions/DisCatSharpException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,15 @@

namespace DisCatSharp.Exceptions;

/// <summary>
/// Represents a generic exception thrown by DisCatSharp.
/// </summary>
public class DisCatSharpException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="DisCatSharpException"/> class.
/// </summary>
/// <param name="message">The error message.</param>
internal DisCatSharpException(string message)
: base(message)
{ }
Expand Down
16 changes: 15 additions & 1 deletion DisCatSharp/Exceptions/ExceptionFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,27 @@

namespace DisCatSharp.Exceptions;

/// <summary>
/// Represents a filter for exceptions that should not be sent to Sentry.
/// </summary>
public class DisCatSharpExceptionFilter : IExceptionFilter
{
internal DiscordConfiguration Config { get; set; }
/// <summary>
/// Gets or sets the configuration.
/// </summary>
internal DiscordConfiguration Config { get; }

/// <summary>
/// Gets whether this filter shoulod track the exception.
/// </summary>
/// <param name="ex">The exception to check.</param>
public bool Filter(Exception ex)
=> !this.Config.TrackExceptions.Contains(ex.GetType());

/// <summary>
/// Initializes a new instance of the <see cref="DisCatSharpExceptionFilter"/> class.
/// </summary>
/// <param name="configuration">The discord configuration.</param>
internal DisCatSharpExceptionFilter(DiscordConfiguration configuration)
{
this.Config = configuration;
Expand Down
4 changes: 2 additions & 2 deletions DisCatSharp/Exceptions/NotFoundException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class NotFoundException : DisCatSharpException
/// <summary>
/// Gets the JSON received.
/// </summary>
public string JsonMessage { get; internal set; }
public string? JsonMessage { get; internal set; } = null;

/// <summary>
/// Initializes a new instance of the <see cref="NotFoundException"/> class.
Expand All @@ -42,7 +42,7 @@ internal NotFoundException(BaseRestRequest request, RestResponse response)
var j = JObject.Parse(response.Response);

if (j["message"] != null)
this.JsonMessage = j["message"].ToString();
this.JsonMessage = j["message"]!.ToString();
}
catch (Exception)
{ }
Expand Down
4 changes: 2 additions & 2 deletions DisCatSharp/Exceptions/RateLimitException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class RateLimitException : DisCatSharpException
/// <summary>
/// Gets the JSON received.
/// </summary>
public string JsonMessage { get; internal set; }
public string? JsonMessage { get; internal set; }

/// <summary>
/// Initializes a new instance of the <see cref="RateLimitException"/> class.
Expand All @@ -42,7 +42,7 @@ internal RateLimitException(BaseRestRequest request, RestResponse response)
var j = JObject.Parse(response.Response);

if (j["message"] != null)
this.JsonMessage = j["message"].ToString();
this.JsonMessage = j["message"]!.ToString();
}
catch (Exception)
{ }
Expand Down
4 changes: 2 additions & 2 deletions DisCatSharp/Exceptions/RequestSizeException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class RequestSizeException : DisCatSharpException
/// <summary>
/// Gets the JSON received.
/// </summary>
public string JsonMessage { get; internal set; }
public string? JsonMessage { get; internal set; }

/// <summary>
/// Initializes a new instance of the <see cref="RequestSizeException"/> class.
Expand All @@ -42,7 +42,7 @@ internal RequestSizeException(BaseRestRequest request, RestResponse response)
var j = JObject.Parse(response.Response);

if (j["message"] != null)
this.JsonMessage = j["message"].ToString();
this.JsonMessage = j["message"]!.ToString();
}
catch (Exception)
{ }
Expand Down
4 changes: 2 additions & 2 deletions DisCatSharp/Exceptions/ServerErrorException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class ServerErrorException : DisCatSharpException
/// <summary>
/// Gets the JSON received.
/// </summary>
public string JsonMessage { get; internal set; }
public string? JsonMessage { get; internal set; }

/// <summary>
/// Initializes a new instance of the <see cref="ServerErrorException"/> class.
Expand All @@ -42,7 +42,7 @@ internal ServerErrorException(BaseRestRequest request, RestResponse response)
var j = JObject.Parse(response.Response);

if (j["message"] != null)
this.JsonMessage = j["message"].ToString();
this.JsonMessage = j["message"]!.ToString();
}
catch (Exception)
{ }
Expand Down
4 changes: 2 additions & 2 deletions DisCatSharp/Exceptions/UnauthorizedException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class UnauthorizedException : DisCatSharpException
/// <summary>
/// Gets the JSON received.
/// </summary>
public string JsonMessage { get; internal set; }
public string? JsonMessage { get; internal set; }

/// <summary>
/// Initializes a new instance of the <see cref="UnauthorizedException"/> class.
Expand All @@ -42,7 +42,7 @@ internal UnauthorizedException(BaseRestRequest request, RestResponse response)
var j = JObject.Parse(response.Response);

if (j["message"] != null)
this.JsonMessage = j["message"].ToString();
this.JsonMessage = j["message"]!.ToString();
}
catch (Exception)
{ }
Expand Down
7 changes: 4 additions & 3 deletions DisCatSharp/Formatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public static string MultiQuote(this string content)
/// <param name="content">Array of strings to transform into a list.</param>
/// <returns>Formatted text.</returns>
public static string SimpleList(this string[] content)
=> string.Join("\n", content.Select(x => $"* {x}"));
=> string.Join("\n", content.Select(x => $"- {x}"));

/// <summary>
/// Creates a URL that won't create a link preview.
Expand All @@ -160,9 +160,10 @@ public static string EmbedlessUrl(this Uri url)
/// <param name="text">Text to display the link as.</param>
/// <param name="url">Url that the link will lead to.</param>
/// <param name="altText">Alt text to display on hover.</param>
/// <param name="embedless">Whether to supress url embeds.</param>
/// <returns>Formatted url.</returns>
public static string MaskedUrl(this string text, Uri url, string altText = "")
=> $"[{text}]({url}{(!string.IsNullOrWhiteSpace(altText) ? $" \"{altText}\"" : "")})";
public static string MaskedUrl(this string text, Uri url, string? altText = null, bool embedless = false)
=> $"[{text}]({(embedless ? EmbedlessUrl(url) : url)}{(!string.IsNullOrWhiteSpace(altText) ? $" \"{altText}\"" : string.Empty)})";

/// <summary>
/// Escapes all markdown formatting from specified text.
Expand Down
14 changes: 10 additions & 4 deletions DisCatSharp/ImageTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,15 @@ public sealed class ImageTool : IDisposable
/// </summary>
public Stream SourceStream { get; }

private ImageFormat _ifcache;
private string _b64Cache;
/// <summary>
/// Gets the format of this image.
/// </summary>
private ImageFormat _ifcache = ImageFormat.Unknown;

/// <summary>
/// Gets the base64 string of this image.
/// </summary>
private string? _b64Cache;

/// <summary>
/// Creates a new image tool from given stream.
Expand All @@ -84,8 +91,7 @@ public ImageTool(Stream stream)
this.SourceStream = stream;
this.SourceStream.Seek(0, SeekOrigin.Begin);

this._ifcache = 0;
this._b64Cache = null!;
this._b64Cache = null;
}

/// <summary>
Expand Down
7 changes: 4 additions & 3 deletions DisCatSharp/Logging/CompositeDefaultLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ internal class CompositeDefaultLogger : ILogger<BaseDiscordClient>
/// <param name="providers">The providers.</param>
public CompositeDefaultLogger(IEnumerable<ILoggerProvider> providers)
{
this._loggers = providers.Select(x => x.CreateLogger(typeof(BaseDiscordClient).FullName))
this._loggers = providers.Select(x => x.CreateLogger(typeof(BaseDiscordClient).FullName!))
.OfType<ILogger<BaseDiscordClient>>()
.ToList();
}
Expand All @@ -42,7 +42,7 @@ public bool IsEnabled(LogLevel logLevel)
/// <param name="state">The state.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatter">The formatter.</param>
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
foreach (var logger in this._loggers)
logger.Log(logLevel, eventId, state, exception, formatter);
Expand All @@ -52,5 +52,6 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
/// Begins the scope.
/// </summary>
/// <param name="state">The state.</param>
public IDisposable BeginScope<TState>(TState state) => throw new NotImplementedException();
public IDisposable BeginScope<TState>(TState state) where TState : notnull
=> throw new NotImplementedException();
}
Loading

0 comments on commit 06db7b0

Please sign in to comment.