Skip to content

Commit

Permalink
- Reuse the Random instance
Browse files Browse the repository at this point in the history
- Fix CA1819 by using ImmutableArray
- Prefer ResponseHeadersRead over ResponseContentRead
- Dispose HttpResponseMessages
- Use HttpClient's default TimeOut
- To fix CA5399 set CheckCertificateRevocationList to true
  • Loading branch information
rampaa committed Jul 21, 2023
1 parent 97e3f63 commit 27b5874
Show file tree
Hide file tree
Showing 9 changed files with 34 additions and 31 deletions.
5 changes: 3 additions & 2 deletions JL.Core/Anki/AnkiConfig.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Immutable;
using System.Text.Json;
using System.Text.Json.Serialization;
using JL.Core.Utilities;
Expand All @@ -12,11 +13,11 @@ public sealed class AnkiConfig

[JsonPropertyName("fields")] public Dictionary<string, JLField> Fields { get; }

[JsonPropertyName("tags")] public string[] Tags { get; }
[JsonPropertyName("tags")] public ImmutableArray<string> Tags { get; }

[JsonIgnore] private static Dictionary<MineType, AnkiConfig>? s_ankiConfigDict;

public AnkiConfig(string deckName, string modelName, Dictionary<string, JLField> fields, string[] tags)
public AnkiConfig(string deckName, string modelName, Dictionary<string, JLField> fields, ImmutableArray<string> tags)
{
DeckName = deckName;
ModelName = modelName;
Expand Down
5 changes: 2 additions & 3 deletions JL.Core/Anki/AnkiConnect.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,8 @@ public static async Task Sync()
using StringContent payload = new(JsonSerializer.Serialize(req, Utils.s_defaultJso));
Utils.Logger.Information("Sending: {Payload}", await payload.ReadAsStringAsync().ConfigureAwait(false));

HttpResponseMessage postResponse = await Networking.Client
.PostAsync(CoreConfig.AnkiConnectUri, payload)
.ConfigureAwait(false);
using HttpResponseMessage postResponse = await Networking.Client
.PostAsync(CoreConfig.AnkiConnectUri, payload).ConfigureAwait(false);

if (postResponse.IsSuccessStatusCode)
{
Expand Down
5 changes: 3 additions & 2 deletions JL.Core/Anki/Note.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Immutable;
using System.Text.Json.Serialization;

namespace JL.Core.Anki;
Expand All @@ -12,7 +13,7 @@ internal sealed class Note

[JsonPropertyName("options")] public Dictionary<string, object> Options { get; }

[JsonPropertyName("tags")] public string[] Tags { get; }
[JsonPropertyName("tags")] public ImmutableArray<string> Tags { get; }

[JsonPropertyName("audio")] public Dictionary<string, object>? Audio { get; }

Expand All @@ -25,7 +26,7 @@ public Note(
string modelName,
Dictionary<string, object> fields,
Dictionary<string, object> options,
string[] tags,
ImmutableArray<string> tags,
Dictionary<string, object>? audio,
Dictionary<string, object>? video,
Dictionary<string, object>? picture
Expand Down
4 changes: 2 additions & 2 deletions JL.Core/Audio/AudioUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public static class AudioUtils
{
try
{
HttpResponseMessage response = await Networking.Client.GetAsync(url).ConfigureAwait(false);
using HttpResponseMessage response = await Networking.Client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

if (response.IsSuccessStatusCode)
{
Expand Down Expand Up @@ -64,7 +64,7 @@ public static class AudioUtils
{
try
{
HttpResponseMessage response = await Networking.Client.GetAsync(url).ConfigureAwait(false);
using HttpResponseMessage response = await Networking.Client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

if (response.IsSuccessStatusCode)
{
Expand Down
2 changes: 1 addition & 1 deletion JL.Core/Dicts/EDICT/ResourceUpdater.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ internal static async Task<bool> UpdateResource(string resourcePath, Uri resourc
"Info");
}

HttpResponseMessage response = await Networking.Client.SendAsync(request).ConfigureAwait(false);
using HttpResponseMessage response = await Networking.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
Stream responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
Expand Down
2 changes: 2 additions & 0 deletions JL.Core/Dicts/IDictRecord.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
namespace JL.Core.Dicts;

#pragma warning disable CA1040
public interface IDictRecord
{
}
#pragma warning restore CA1040
4 changes: 2 additions & 2 deletions JL.Core/Network/Networking.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace JL.Core.Network;

public static class Networking
{
public static readonly HttpClient Client = new(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromMinutes(10) };
public static readonly HttpClient Client = new(new HttpClientHandler { UseProxy = false, CheckCertificateRevocationList = true });
internal const string Jpod101NoAudioMd5Hash = "7E-2C-2F-95-4E-F6-05-13-73-BA-91-6F-00-01-68-DC";
private static readonly Uri s_gitHubApiUrlForLatestJLRelease = new("https://api.github.com/repos/rampaa/JL/releases/latest");

Expand All @@ -17,7 +17,7 @@ public static async Task CheckForJLUpdates(bool isAutoCheck)
using HttpRequestMessage gitHubApiRequest = new(HttpMethod.Get, s_gitHubApiUrlForLatestJLRelease);
gitHubApiRequest.Headers.Add("User-Agent", "JL");

HttpResponseMessage gitHubApiResponse = await Client.SendAsync(gitHubApiRequest).ConfigureAwait(false);
using HttpResponseMessage gitHubApiResponse = await Client.SendAsync(gitHubApiRequest, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

if (gitHubApiResponse.IsSuccessStatusCode)
{
Expand Down
7 changes: 4 additions & 3 deletions JL.Windows/GUI/PreferencesWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Immutable;
using System.Globalization;
using System.Text;
using System.Windows;
Expand Down Expand Up @@ -305,9 +306,9 @@ private static void CreateFieldElements(Dictionary<string, JLField> fields, IEnu
}

string rawTags = tagsTextBox.Text;
string[] tags = string.IsNullOrEmpty(rawTags)
? Array.Empty<string>()
: rawTags.Split(',').Select(static s => s.Trim()).ToArray();
ImmutableArray<string> tags = string.IsNullOrEmpty(rawTags)
? ImmutableArray<string>.Empty
: rawTags.Split(',').Select(static s => s.Trim()).ToImmutableArray();

return new AnkiConfig(deckName, modelName, dict, tags);
}
Expand Down
31 changes: 15 additions & 16 deletions JL.Windows/Utilities/WindowsUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ namespace JL.Windows.Utilities;

internal static class WindowsUtils
{
private static readonly Random s_random = new();
private static DateTime s_lastAudioPlayTime = new();
public static WaveOut? AudioPlayer { get; private set; }

Expand Down Expand Up @@ -264,23 +265,22 @@ public static void SearchWithBrowser(string? selectedText)

public static async Task UpdateJL(Uri latestReleaseUrl)
{
using HttpRequestMessage downloadRequest = new(HttpMethod.Get, latestReleaseUrl);
HttpResponseMessage downloadResponse = await Networking.Client.SendAsync(downloadRequest).ConfigureAwait(false);
using HttpResponseMessage downloadResponse = await Networking.Client.GetAsync(latestReleaseUrl, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

if (downloadResponse.IsSuccessStatusCode)
{
Stream downloadResponseStream = await downloadResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
await using (downloadResponseStream.ConfigureAwait(false))
{
string tmpDirectory = Path.Join(Utils.ApplicationPath, "tmp");
string tmpDirectory = Path.Join(Utils.ApplicationPath, "tmp");

if (Directory.Exists(tmpDirectory))
{
Directory.Delete(tmpDirectory, true);
}
if (Directory.Exists(tmpDirectory))
{
Directory.Delete(tmpDirectory, true);
}

_ = Directory.CreateDirectory(tmpDirectory);
_ = Directory.CreateDirectory(tmpDirectory);

Stream downloadResponseStream = await downloadResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
await using (downloadResponseStream.ConfigureAwait(false))
{
using ZipArchive archive = new(downloadResponseStream);
archive.ExtractToDirectory(tmpDirectory);
}
Expand Down Expand Up @@ -352,7 +352,6 @@ public static void PlayAudio(byte[] audio, string audioFormat, float volume)
});
}

#pragma warning disable CA5394
public static async Task Motivate()
{
DateTime currentTime = DateTime.Now;
Expand All @@ -366,8 +365,6 @@ public static async Task Motivate()

try
{
Random rand = new();

string[] filePaths = Directory.GetFiles(Path.Join(Utils.ResourcesPath, "Motivation"));
int numFiles = filePaths.Length;

Expand All @@ -378,7 +375,10 @@ public static async Task Motivate()
return;
}

string randomFilePath = filePaths[rand.Next(numFiles)];
#pragma warning disable CA5394
string randomFilePath = filePaths[s_random.Next(numFiles)];
#pragma warning restore CA5394

byte[] audioData = await File.ReadAllBytesAsync(randomFilePath).ConfigureAwait(false);
PlayAudio(audioData, "mp3", 1);
Stats.IncrementStat(StatType.Imoutos);
Expand All @@ -389,7 +389,6 @@ public static async Task Motivate()
Utils.Frontend.Alert(AlertLevel.Error, "Error motivating");
}
}
#pragma warning restore CA5394

public static Brush? BrushFromHex(string hexColorString)
{
Expand Down

0 comments on commit 27b5874

Please sign in to comment.