-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLastFMApi.cs
More file actions
76 lines (62 loc) · 2.24 KB
/
LastFMApi.cs
File metadata and controls
76 lines (62 loc) · 2.24 KB
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
73
74
75
76
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace EpikLastFMApi
{
class LastFMApi
{
public const string BaseURL = "https://ws.audioscrobbler.com/2.0/";
private readonly string _key;
public LastFMApi(string key)
{
_key = key;
}
public async Task<string> AlbumSearchAsync(Func<JObject, string, string, string> findValue, string album, string artist = "")
{
try
{
if (string.IsNullOrWhiteSpace(album))
return null;
string url = $"{BaseURL}?method=album.search&album={_uriEnc(album)}";
JObject json = await _jsonResponseAsync(url);
return findValue(json, artist, album);
}
catch
{
return null;
}
}
public async Task<string> AlbumGetInfoAsync(Func<JObject, string> findValue, string album, string artist = "", string track = "")
{
try
{
if (string.IsNullOrWhiteSpace(album) || string.IsNullOrWhiteSpace(artist))
return null;
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 _jsonResponseAsync(url);
return findValue(json);
}
catch
{
return null;
}
}
private async Task<JObject> _jsonResponseAsync(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());
else
throw new HttpRequestException();
}
}
private string _uriEnc(string a) => Uri.EscapeDataString(a);
}
}