-
Notifications
You must be signed in to change notification settings - Fork 2
/
LastFM_API.cs
72 lines (61 loc) · 2.22 KB
/
LastFM_API.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace EpikLastFMApi
{
class LastFM_API
{
private string BaseURL = "https://ws.audioscrobbler.com/2.0/";
private string key { get; set; }
public LastFM_API(string _key) { key = _key; }
public async Task<string> AlbumSearch(Func<JObject, string, string, string> FindValue, string Album, string Artist = "")
{
try
{
if (string.IsNullOrWhiteSpace(Album))
throw new ArgumentNullException();
string Url = $"{BaseURL}?method=album.search&album={UriEnc(Album)}";
JObject Json = await JsonResponse(Url);
return FindValue(Json, Artist, Album);
}
catch
{
return "";
}
}
public async Task<string> AlbumGetInfo(Func<JObject, string> FindValue, string Album, string Artist = "", string Track = "")
{
try
{
if (string.IsNullOrWhiteSpace(Album) | string.IsNullOrWhiteSpace(Artist))
throw new ArgumentNullException();
string Url = $"{BaseURL}?method=album.getinfo&album={UriEnc(Album)}";
if (!string.IsNullOrWhiteSpace(Artist))
Url += $"&artist={UriEnc(Artist)}";
if (!string.IsNullOrWhiteSpace(Track))
Url += $"&track={UriEnc(Track)}";
JObject Json = await JsonResponse(Url);
return FindValue(Json);
}
catch
{
return "";
}
}
private async Task<JObject> JsonResponse(string url)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage Resp = await client.GetAsync(url + $"&api_key={key}&format=json");
if (Resp.IsSuccessStatusCode)
return JObject.Parse(await Resp.Content.ReadAsStringAsync());
}
throw new HttpRequestException();
}
private string UriEnc(string a)
{
return Uri.EscapeDataString(a);
}
}
}