forked from jonentropy/hgdc-x
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lastfm.pas
executable file
·290 lines (238 loc) · 7.62 KB
/
lastfm.pas
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
{
* Copyright (c) 2012, Tristan Linnell <tris@canthack.org>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
}
// hgdc-x Cross Platform hgd client written in Lazarus/Freepascal
// lastfm.pas - Last.fm web service client for scrobbling and album
// art fetching.
unit LastFM;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ExtCtrls, HTTPSend, SynaCode, XMLRead, DOM, FileUtil,
LCLProc;
const
API_ROOT_URL = 'http://ws.audioscrobbler.com/2.0/';
API_KEY = 'd73bc1bcce5c08bd73c5f941480845e8';
API_SECRET = 'SECRET_HERE';
type
TLastFMSong = record
Artist: string;
Album: string;
Duration: integer;
TimeListened: TDateTime;
end;
TLastFMAlbumSize = (szSmall, szMedium, szLarge, szExtraLarge, szMega);
{ TLastFM }
TLastFM = class(TObject)
private
FUserName: string;
FCacheDirectory: string;
FDebug: boolean;
FScrobbleTimer: TTimer;
FNowPlayingSong: TLastFMSong;
FScrobbleList: TList;
procedure Log(Message: String);
function ReplaceIllegalFilenameChars(Input: string): string;
procedure ScrobbleTimer(Sender: TObject);
procedure SetPlayingSong(Song: TLastFMSong);
public
function GetAlbumArt(Artist, Album: string; Size: TLastFMAlbumSize;
var CoverImage: TImage): boolean;
constructor Create; overload;
constructor Create(User: string); overload;
constructor Create(User: string; CacheDirectory: string;
Debug: boolean); overload;
destructor Destroy; override;
end;
implementation
{ TLastFM }
function TLastFM.GetAlbumArt(Artist, Album: string; Size: TLastFMAlbumSize;
var CoverImage: TImage): boolean;
var
Connection: THTTPSend;
RequestURL: string;
XMLResponse: TXMLDocument;
Node: TDOMNode;
Found: boolean;
CoverURL: string;
ImStr: string;
CacheName: string;
begin
Result := False;
CacheName := FCacheDirectory + ReplaceIllegalFilenameChars(Artist +
'-' + Album) + '.png';
if (FCacheDirectory <> '') and
(FileExistsUTF8(CacheName)) then
begin
Log('Album art is cached (' + CacheName + '), not requesting album art.');
CoverImage.Picture.LoadFromFile(CacheName);
Exit(True);
end;
Log('Attempting to get artwork from Last.fm');
Connection := THTTPSend.Create();
XMLResponse := TXMLDocument.Create();
CoverURL := '';
try
Connection.Timeout := 1000;
RequestURL := API_ROOT_URL + '?method=album.getinfo&api_key=' + API_KEY +
'&artist=' + EncodeURLElement(Artist) + '&album=' +
EncodeURLElement(Album) + '&autocorrect=1';
Connection.Clear;
if Connection.HTTPMethod('GET', RequestURL) and (Connection.ResultCode = 200) then
begin
try
Log('Got XML response for album ' + Album + ' by ' + Artist);
ReadXMLFile(XMLResponse, Connection.Document);
//Check status code from Last.fm
Node := XMLResponse.DocumentElement.FindNode('lfm');
if Assigned(Node) and (Node.Attributes.Item[0].NodeName = 'status') and
(Node.Attributes.Item[0].NodeValue = 'failed') then
begin
//Failure...
Log('Last.fm API call failed');
Node := XMLResponse.DocumentElement.FindNode('error');
Log(Node.FirstChild.NodeValue);
Node := nil;
end
else
Node := XMLResponse.DocumentElement.FindNode('album');
except
Node := nil;
end;
if Assigned(Node) then
begin
Node := Node.FindNode('image');
Found := False;
case Size of
szSmall: ImStr := 'small';
szLarge: ImStr := 'large';
szExtraLarge: ImStr := 'extralarge';
szMega: ImStr := 'mega';
else
ImStr := 'medium';
end;
while (not Found) and (Node.Attributes.Item[0].NodeValue <> ImStr) do
begin
if Node.NextSibling.NodeName = 'image' then
Node := Node.NextSibling
else
Found := True;
end;
if Node.FirstChild <> nil then
CoverURL := Node.FirstChild.NodeValue;
end
else
Log('Last.fm didn''t respond with album art.');
if CoverURL <> '' then
begin
Log('Fetching the album cover image');
//Get the cover
CoverURL := EncodeURL(CoverURL);
Connection.Clear;
if Connection.HTTPMethod('GET', CoverURL) and (Connection.ResultCode = 200) then
begin
Log('Album art downloaded, caching...');
try
CoverImage.Picture.LoadFromStream(Connection.Document);
//Cache album art...
if (FCacheDirectory <> '') and
DirectoryIsWritable(FCacheDirectory) then
begin
CoverImage.Picture.SaveToFile(CacheName, 'png');
Result := True;
end
else
Log('There was a problem caching the album art.');
except
Log('Exception when loading image from stream.');
end;
end;
end
else
log('No URL found for album art.');
end
else
begin
Log('Last.fm GET request failed : ' + Connection.ResultString);
end;
finally
XMLResponse.Free();
Connection.Free();
end;
end;
constructor TLastFM.Create;
begin
inherited Create();
FScrobbleList := TList.Create;
FScrobbleTimer := TTimer.Create(nil);
FScrobbleTimer.Interval := 2000;
FScrobbleTimer.Enabled := False;
FScrobbleTimer.OnTimer := @ScrobbleTimer;
end;
constructor TLastFM.Create(User: string);
begin
FUserName := User;
Create();
end;
constructor TLastFM.Create(User: string; CacheDirectory: string;
Debug: boolean);
begin
if ForceDirectoriesUTF8(CacheDirectory) then
FCacheDirectory := CacheDirectory
else
FCacheDirectory := '';
FDebug := Debug;
Create(User);
end;
procedure TLastFM.SetPlayingSong(Song: TLastFMSong);
begin
FNowPlayingSong := Song;
end;
procedure TLastFM.ScrobbleTimer(Sender: TObject);
begin
//if song has been set
// set now playing
//inc time
//if time > duration/2 then add to scrobble list
//for all in scrobble list,
//try and scrobble
//if succesful remove from list
//
end;
destructor TLastFM.Destroy;
begin
//save scobble list...
FScrobbleList.Free();
FScrobbleTimer.Free();
inherited Destroy();
end;
procedure TLastFM.Log(Message: string);
begin
if FDebug then
DebugLn(Self.ClassName + #9#9 + Message);
end;
function TLastFM.ReplaceIllegalFilenameChars(Input: string): string;
begin
Result := StringReplace(Input, '/', '-', [rfReplaceAll]);
Result := StringReplace(Result, '\', '-', [rfReplaceAll]);
Result := StringReplace(Result, ':', '-', [rfReplaceAll]);
Result := StringReplace(Result, '*', '-', [rfReplaceAll]);
Result := StringReplace(Result, '<', '-', [rfReplaceAll]);
Result := StringReplace(Result, '>', '-', [rfReplaceAll]);
Result := StringReplace(Result, '?', '-', [rfReplaceAll]);
Result := StringReplace(Result, '"', '-', [rfReplaceAll]);
Result := StringReplace(Result, '|', '-', [rfReplaceAll]);
end;
end.