Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
d4n3436 committed Aug 19, 2024
1 parent 992ea92 commit 8fb08c4
Show file tree
Hide file tree
Showing 16 changed files with 113 additions and 125 deletions.
2 changes: 1 addition & 1 deletion src/Apis/Bing/BingVisualSearch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Fergun.Extensions;

namespace Fergun.Apis.Bing;

Expand Down Expand Up @@ -150,6 +149,7 @@ public void Dispose()
private static JsonElement GetImageTag(JsonDocument document, string displayName) => document
.RootElement
.GetProperty("tags"u8)
.EnumerateArray()
.FirstOrDefault(x => x.GetProperty("displayName"u8).ValueEquals(displayName));

private static HttpRequestMessage BuildRequest(string url, string invokedSkill, BingSafeSearchLevel safeSearch = BingSafeSearchLevel.Moderate, string? language = null)
Expand Down
10 changes: 5 additions & 5 deletions src/Apis/Genius/LyricsConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonS
{
var builder = new StringBuilder();
var dom = JsonElement.ParseValue(ref reader)
.GetProperty("dom");
.GetProperty("dom"u8);

IterateContent(dom, builder);
return builder.ToString();
Expand All @@ -44,15 +44,15 @@ private static void IterateContent(in JsonElement element, StringBuilder builder
}
else if (element.ValueKind == JsonValueKind.Object) // either tag or tag + children
{
string? tag = element.GetProperty("tag").GetString();
bool realLink = element.TryGetProperty("data", out var data) && data.TryGetProperty("real-link", out var realLinkProp) && realLinkProp.ValueEquals("true");
string? tag = element.GetProperty("tag"u8).GetString();
bool realLink = element.TryGetProperty("data"u8, out var data) && data.TryGetProperty("real-link"u8, out var realLinkProp) && realLinkProp.ValueEquals("true"u8);

(string? markDownStart, string? markDownEnd) = tag switch
{
ITALIC => ("*", "*"),
BOLD => ("**", "**"),
LINE_BREAK or HORIZONTAL_LINE or IMAGE or DFP_UNIT => ("\n", null),
LINK when realLink => ("[", $"]({element.GetProperty("attributes").GetProperty("href").GetString()})"),
LINK when realLink => ("[", $"]({element.GetProperty("attributes"u8).GetProperty("href"u8).GetString()})"),
UNDERLINE => ("__", "__"),
"h1" => ("\n# ", "\n"),
"h2" => ("\n## ", "\n"),
Expand All @@ -67,7 +67,7 @@ private static void IterateContent(in JsonElement element, StringBuilder builder

builder.Append(markDownStart);

if (element.TryGetProperty("children", out var children))
if (element.TryGetProperty("children"u8, out var children))
{
Debug.Assert(children.ValueKind == JsonValueKind.Array);

Expand Down
2 changes: 1 addition & 1 deletion src/Apis/Google/GoogleLensClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public async Task<string> OcrAsync(string url, CancellationToken cancellationTok
return string.Empty;
}

return string.Join('\n', data[0].EnumerateArray().Select(x => x.GetString()));
return string.Join('\n', data[0].Deserialize<string[]>()!);
}

/// <inheritdoc/>
Expand Down
78 changes: 39 additions & 39 deletions src/Apis/Musixmatch/MusixmatchClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,11 @@ public async Task<IReadOnlyList<IMusixmatchSong>> SearchSongsAsync(string query,

return document
.RootElement
.GetProperty("message")
.GetProperty("body")
.GetProperty("track_list")
.GetProperty("message"u8)
.GetProperty("body"u8)
.GetProperty("track_list"u8)
.EnumerateArray()
.Select(x => x.GetProperty("track").Deserialize<MusixmatchSong>()!)
.Select(x => x.GetProperty("track"u8).Deserialize<MusixmatchSong>()!)
.ToArray();
}

Expand All @@ -84,15 +84,15 @@ public async Task<IReadOnlyList<IMusixmatchSong>> SearchSongsAsync(string query,

var macroCalls = document
.RootElement
.GetProperty("message")
.GetProperty("body")
.GetProperty("macro_calls")[0];
.GetProperty("message"u8)
.GetProperty("body"u8)
.GetProperty("macro_calls"u8)[0];

var trackStatusCode = (HttpStatusCode)macroCalls
.GetProperty("track.get")
.GetProperty("message")
.GetProperty("header")
.GetProperty("status_code")
.GetProperty("track.get"u8)
.GetProperty("message"u8)
.GetProperty("header"u8)
.GetProperty("status_code"u8)
.GetInt32();

if (trackStatusCode == HttpStatusCode.NotFound)
Expand All @@ -101,43 +101,43 @@ public async Task<IReadOnlyList<IMusixmatchSong>> SearchSongsAsync(string query,
}

var lyricsStatusCode = (HttpStatusCode)macroCalls
.GetProperty("track.lyrics.get")
.GetProperty("message")
.GetProperty("header")
.GetProperty("status_code")
.GetProperty("track.lyrics.get"u8)
.GetProperty("message"u8)
.GetProperty("header"u8)
.GetProperty("status_code"u8)
.GetInt32();

var lyricsData = lyricsStatusCode == HttpStatusCode.NotFound ? default : macroCalls
.GetProperty("track.lyrics.get")
.GetProperty("message")
.GetProperty("body")
.GetProperty("lyrics");
.GetProperty("track.lyrics.get"u8)
.GetProperty("message"u8)
.GetProperty("body"u8)
.GetProperty("lyrics"u8);

string? lyrics = lyricsStatusCode == HttpStatusCode.NotFound ? null : lyricsData
.GetProperty("lyrics_body")
.GetProperty("lyrics_body"u8)
.GetString();

var trackData = macroCalls
.GetProperty("track.get")
.GetProperty("message")
.GetProperty("body")
.GetProperty("track");
.GetProperty("track.get"u8)
.GetProperty("message"u8)
.GetProperty("body"u8)
.GetProperty("track"u8);

bool isRestricted = lyricsStatusCode == HttpStatusCode.NotFound ? trackData
.GetProperty("restricted")
.GetProperty("restricted"u8)
.GetInt32() != 0 : lyricsData
.GetProperty("restricted")
.GetProperty("restricted"u8)
.GetInt32() != 0;

string artistName = trackData.GetProperty("artist_name").GetString()!;
bool isInstrumental = trackData.GetProperty("instrumental").GetInt32() != 0;
bool hasLyrics = trackData.GetProperty("has_lyrics").GetInt32() != 0;
string? songArtImageUrl = trackData.GetProperty("album_coverart_500x500").GetString();
string title = trackData.GetProperty("track_name").GetString()!;
int artistId = trackData.GetProperty("artist_id").GetInt32();
string artistName = trackData.GetProperty("artist_name"u8).GetString()!;
bool isInstrumental = trackData.GetProperty("instrumental"u8).GetInt32() != 0;
bool hasLyrics = trackData.GetProperty("has_lyrics"u8).GetInt32() != 0;
string? songArtImageUrl = trackData.GetProperty("album_coverart_500x500"u8).GetString();
string title = trackData.GetProperty("track_name"u8).GetString()!;
int artistId = trackData.GetProperty("artist_id"u8).GetInt32();

string? spotifyTrackId = null;
if (trackData.TryGetProperty("track_spotify_id", out var trackIdProp))
if (trackData.TryGetProperty("track_spotify_id"u8, out var trackIdProp))
{
spotifyTrackId = trackIdProp.GetString();
}
Expand Down Expand Up @@ -167,17 +167,17 @@ public void Dispose()
internal static void ThrowIfNotSuccessful(in JsonElement body, string? path = null)
{
var header = body
.GetProperty("message")
.GetProperty("header");
.GetProperty("message"u8)
.GetProperty("header"u8);

var statusCode = (HttpStatusCode)header
.GetProperty("status_code")
.GetProperty("status_code"u8)
.GetInt32();

if (statusCode is HttpStatusCode.OK or HttpStatusCode.NotFound) return;

string? hint = header
.GetProperty("hint")
.GetProperty("hint"u8)
.GetString();

MusixmatchException.Throw(statusCode, path, hint);
Expand All @@ -198,8 +198,8 @@ private async Task<JsonDocument> SendRequestAndValidateAsync(string url, Cancell

ThrowIfNotSuccessful(document.RootElement);

var body = document.RootElement.GetProperty("message").GetProperty("body");
if (body.TryGetProperty("macro_calls", out var macroCalls) && macroCalls.ValueKind == JsonValueKind.Array)
var body = document.RootElement.GetProperty("message"u8).GetProperty("body"u8);
if (body.TryGetProperty("macro_calls"u8, out var macroCalls) && macroCalls.ValueKind == JsonValueKind.Array)
{
foreach (var prop in macroCalls.EnumerateArray())
{
Expand Down
6 changes: 3 additions & 3 deletions src/Apis/Musixmatch/MusixmatchClientState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,9 @@ private async Task<string> FetchUserTokenAsync()

string? token = document
.RootElement
.GetProperty("message")
.GetProperty("body")
.GetProperty("user_token")
.GetProperty("message"u8)
.GetProperty("body"u8)
.GetProperty("user_token"u8)
.GetString();

if (string.IsNullOrEmpty(token) || token == "UpgradeOnlyUpgradeOnlyUpgradeOnlyUpgradeOnly")
Expand Down
10 changes: 5 additions & 5 deletions src/Apis/Urban/UrbanDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public async Task<IReadOnlyList<UrbanDefinition>> GetDefinitionsAsync(string ter

await using var stream = await _httpClient.GetStreamAsync(new Uri($"define?term={Uri.EscapeDataString(term)}", UriKind.Relative), cancellationToken).ConfigureAwait(false);
using var document = await JsonDocument.ParseAsync(stream, default, cancellationToken).ConfigureAwait(false);
return document.RootElement.GetProperty("list").Deserialize<IReadOnlyList<UrbanDefinition>>()!;
return document.RootElement.GetProperty("list"u8).Deserialize<IReadOnlyList<UrbanDefinition>>()!;
}

/// <inheritdoc/>
Expand All @@ -63,7 +63,7 @@ public async Task<IReadOnlyList<UrbanDefinition>> GetRandomDefinitionsAsync(Canc

await using var stream = await _httpClient.GetStreamAsync(new Uri("random", UriKind.Relative), cancellationToken).ConfigureAwait(false);
using var document = await JsonDocument.ParseAsync(stream, default, cancellationToken).ConfigureAwait(false);
return document.RootElement.GetProperty("list").Deserialize<IReadOnlyList<UrbanDefinition>>()!;
return document.RootElement.GetProperty("list"u8).Deserialize<IReadOnlyList<UrbanDefinition>>()!;
}

/// <inheritdoc/>
Expand All @@ -74,7 +74,7 @@ public async Task<IReadOnlyList<UrbanDefinition>> GetRandomDefinitionsAsync(Canc

await using var stream = await _httpClient.GetStreamAsync(new Uri($"define?defid={id}", UriKind.Relative), cancellationToken).ConfigureAwait(false);
using var document = await JsonDocument.ParseAsync(stream, default, cancellationToken).ConfigureAwait(false);
var list = document.RootElement.GetProperty("list");
var list = document.RootElement.GetProperty("list"u8);

return list.GetArrayLength() == 0 ? null : list[0].Deserialize<UrbanDefinition>()!;
}
Expand All @@ -87,7 +87,7 @@ public async Task<IReadOnlyList<UrbanDefinition>> GetWordsOfTheDayAsync(Cancella

await using var stream = await _httpClient.GetStreamAsync(new Uri("words_of_the_day", UriKind.Relative), cancellationToken).ConfigureAwait(false);
using var document = await JsonDocument.ParseAsync(stream, default, cancellationToken).ConfigureAwait(false);
return document.RootElement.GetProperty("list").Deserialize<IReadOnlyList<UrbanDefinition>>()!;
return document.RootElement.GetProperty("list"u8).Deserialize<IReadOnlyList<UrbanDefinition>>()!;
}

/// <inheritdoc/>
Expand All @@ -107,7 +107,7 @@ public async Task<IReadOnlyList<UrbanAutocompleteResult>> GetAutocompleteResults

await using var stream = await _httpClient.GetStreamAsync(new Uri($"autocomplete-extra?term={Uri.EscapeDataString(term)}", UriKind.Relative), cancellationToken).ConfigureAwait(false);
using var document = await JsonDocument.ParseAsync(stream, default, cancellationToken).ConfigureAwait(false);
return document.RootElement.GetProperty("results").Deserialize<IReadOnlyList<UrbanAutocompleteResult>>()!;
return document.RootElement.GetProperty("results"u8).Deserialize<IReadOnlyList<UrbanAutocompleteResult>>()!;
}

/// <inheritdoc/>
Expand Down
10 changes: 5 additions & 5 deletions src/Apis/Wikipedia/WikipediaClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@ public WikipediaClient(HttpClient httpClient)
using var document = await JsonDocument.ParseAsync(stream, default, cancellationToken).ConfigureAwait(false);

var page = document.RootElement
.GetProperty("query")
.GetProperty("pages")[0];
.GetProperty("query"u8)
.GetProperty("pages"u8)[0];

if (page.TryGetProperty("missing", out var missing) && missing.GetBoolean())
if (page.TryGetProperty("missing"u8, out var missing) && missing.GetBoolean())
{
return null;
}
Expand All @@ -83,8 +83,8 @@ public async Task<IReadOnlyList<IPartialWikipediaArticle>> SearchArticlesAsync(s

return document
.RootElement
.GetProperty("query")
.GetProperty("search")
.GetProperty("query"u8)
.GetProperty("search"u8)
.Deserialize<IReadOnlyList<PartialWikipediaArticle>>()!;
}

Expand Down
6 changes: 3 additions & 3 deletions src/Apis/WolframAlpha/WolframAlphaClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ public async Task<IReadOnlyList<string>> GetAutocompleteResultsAsync(string inpu

return document
.RootElement
.GetProperty("results")
.GetProperty("results"u8)
.EnumerateArray()
.Select(x => x.GetProperty("input").GetString()!)
.Select(x => x.GetProperty("input"u8).GetString()!)
.ToArray();
}

Expand All @@ -87,7 +87,7 @@ public async Task<IWolframAlphaResult> SendQueryAsync(string input, string langu

using var document = await JsonDocument.ParseAsync(stream, default, cancellationToken).ConfigureAwait(false);

return document.RootElement.GetProperty("queryresult").Deserialize<WolframAlphaResult>()!;
return document.RootElement.GetProperty("queryresult"u8).Deserialize<WolframAlphaResult>()!;
}

/// <inheritdoc/>
Expand Down
35 changes: 17 additions & 18 deletions src/Apis/Yandex/YandexImageSearch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using System.Threading;
using System.Threading.Tasks;
using AngleSharp.Html.Parser;
using Fergun.Extensions;

namespace Fergun.Apis.Yandex;

Expand Down Expand Up @@ -70,12 +69,12 @@ public YandexImageSearch(HttpClient httpClient)

string? imageId = document
.RootElement
.GetProperty("image_id")
.GetProperty("image_id"u8)
.GetString();

int imageShard = document
.RootElement
.GetProperty("image_shard")
.GetProperty("image_shard"u8)
.GetInt32();

// Get OCR text
Expand All @@ -89,18 +88,18 @@ public YandexImageSearch(HttpClient httpClient)
byte[] bytes = await ocrResponse.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
using var ocrDocument = JsonDocument.Parse(bytes);

if (ocrDocument.RootElement.TryGetProperty("type", out var type) && type.ValueEquals("captcha"))
if (ocrDocument.RootElement.TryGetProperty("type"u8, out var type) && type.ValueEquals("captcha"u8))
{
throw new YandexException("Yandex API returned a CAPTCHA. Try again later.");
}

return ocrDocument
.RootElement
.GetProperty("blocks")[0] // There should be a single block, "i-react-ajax-adapter:ajax"
.GetProperty("params")
.GetPropertyOrDefault("adapterData")
.GetPropertyOrDefault("plainText")
.GetStringOrDefault();
.GetProperty("blocks"u8)[0] // There should be a single block, "i-react-ajax-adapter:ajax"
.GetProperty("params"u8)
.GetProperty("adapterData"u8)
.GetProperty("plainText"u8)
.GetString();
}

/// <inheritdoc/>
Expand Down Expand Up @@ -137,15 +136,15 @@ public async Task<IReadOnlyList<IYandexReverseImageSearchResult>> ReverseImageSe
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var document = await JsonDocument.ParseAsync(stream, default, cancellationToken).ConfigureAwait(false);

if (document.RootElement.TryGetProperty("type", out var type) && type.ValueEquals("captcha"))
if (document.RootElement.TryGetProperty("type"u8, out var type) && type.ValueEquals("captcha"u8))
{
throw new YandexException("Yandex API returned a CAPTCHA. Try again later.");
}

string html = document
.RootElement
.GetProperty("blocks")[0]
.GetProperty("html")
.GetProperty("blocks"u8)[0]
.GetProperty("html"u8)
.GetString()!;

var htmlDocument = await _parser.ParseDocumentAsync(html, cancellationToken).ConfigureAwait(false);
Expand All @@ -163,14 +162,14 @@ public async Task<IReadOnlyList<IYandexReverseImageSearchResult>> ReverseImageSe

using var data = JsonDocument.Parse(json);

if (data.RootElement.TryGetProperty("initialState", out var initialState))
if (data.RootElement.TryGetProperty("initialState"u8, out var initialState))
{
return initialState
.GetProperty("serpList")
.GetProperty("items")
.GetProperty("entities")
.GetProperty("serpList"u8)
.GetProperty("items"u8)
.GetProperty("entities"u8)
.EnumerateObject()
.Select(x => x.Value.GetProperty("viewerData").Deserialize<YandexReverseImageSearchResult>()!)
.Select(x => x.Value.GetProperty("viewerData"u8).Deserialize<YandexReverseImageSearchResult>()!)
.ToArray();
}

Expand All @@ -179,7 +178,7 @@ public async Task<IReadOnlyList<IYandexReverseImageSearchResult>> ReverseImageSe
.GetElementsByClassName("serp-list")
.FirstOrDefault()?
.GetElementsByClassName("serp-item")
.Select(x => JsonDocument.Parse(x.GetAttribute("data-bem")!).RootElement.GetProperty("serp-item").Deserialize<YandexReverseImageSearchResult>()!)
.Select(x => JsonDocument.Parse(x.GetAttribute("data-bem")!).RootElement.GetProperty("serp-item"u8).Deserialize<YandexReverseImageSearchResult>()!)
.ToArray() ?? [];
}

Expand Down
Loading

0 comments on commit 8fb08c4

Please sign in to comment.