Files
Harmony/HarmonyWinUI/Models/MusicBrainz.cs
T

97 lines
2.4 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace HarmonyWinUI.Models
{
class MusicBrainz
{
private String URLprefix = "https://musicbrainz.org/ws/2/";
private static readonly HttpClient httpClient = createHttpClient();
public async Task<List<MusicBrainzArtist>> getArtists(String query)
{
ArgumentException.ThrowIfNullOrWhiteSpace(query);
string searchQuery = Uri.EscapeDataString($"artist:{query}");
MusicBrainzArtistResponse? response = await getData<MusicBrainzArtistResponse>(
$"artist?query={searchQuery}&fmt=json&limit=10"
);
return response?.Artists ?? new List<MusicBrainzArtist>();
}
private async Task<T?> getData<T>(String relativeURL)
{
Uri requestURL = new Uri(new Uri(URLprefix), relativeURL);
using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestURL);
using HttpResponseMessage response = await httpClient.SendAsync(
request,
HttpCompletionOption.ResponseHeadersRead
);
response.EnsureSuccessStatusCode();
await using Stream jsonStream = await response.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync<T>(jsonStream);
}
private static HttpClient createHttpClient()
{
HttpClient client = new HttpClient
{
Timeout = TimeSpan.FromSeconds(30)
};
client.DefaultRequestHeaders.UserAgent.ParseAdd(
"HarmonyWinUI/1.0 (https://harmony.tpsoft.org/)"
);
return client;
}
private sealed class MusicBrainzArtistResponse
{
[JsonPropertyName("artists")]
public List<MusicBrainzArtist>? Artists { get; set; }
}
}
public class MusicBrainzArtist
{
public string? ID { get; set; }
public string? Type { get; set; }
[JsonPropertyName("type-id")]
public string? TypeID { get; set; }
public int? Score { get; set; }
public string? Name { get; set; } = "";
public string? Gender { get; set; }
public string? Country { get; set; }
public string? ImageURL { get; set; }
public MusicBrainzArtist() { }
public MusicBrainzArtist(
string? id,
string? type,
string? typeID,
int? score,
string? name,
string? gender,
string? country)
{
this.ID = id;
this.Type = type;
this.TypeID = typeID;
this.Score = score;
this.Name = name;
this.Gender = gender;
this.Country = country;
}
}
}