3 * AudioscrobblerController
4 * Audioscrobbler Support Class
6 * Original Author : Kent Sutherland <kent.sutherland@ithinksw.com>
7 * Responsibility : Kent Sutherland <kent.sutherland@ithinksw.com>
9 * Copyright (c) 2005 iThink Software.
14 #import "AudioscrobblerController.h"
15 #import "PreferencesController.h"
16 #import <openssl/evp.h>
17 #import <ITFoundation/ITDebug.h>
19 #define AUDIOSCROBBLER_ID @"mtu"
20 #define AUDIOSCROBBLER_VERSION [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]
22 static AudioscrobblerController *_sharedController = nil;
24 @implementation AudioscrobblerController
26 + (AudioscrobblerController *)sharedController
28 if (!_sharedController) {
29 _sharedController = [[AudioscrobblerController alloc] init];
31 return _sharedController;
36 if ( (self = [super init]) ) {
37 _handshakeCompleted = NO;
41 /*_handshakeCompleted = YES;
42 _md5Challenge = @"rawr";
43 _postURL = [NSURL URLWithString:@"http://audioscrobbler.com/"];*/
45 _delayDate = [[NSDate date] retain];
47 _tracks = [[NSMutableArray alloc] init];
48 _submitTracks = [[NSMutableArray alloc] init];
49 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioscrobblerNotification:) name:@"AudioscrobblerHandshakeComplete" object:self];
56 [_lastStatus release];
57 [_md5Challenge release];
59 [_responseData release];
60 [_submitTracks release];
66 - (NSString *)lastStatus
71 - (void)attemptHandshake
73 [self attemptHandshake:NO];
76 - (void)attemptHandshake:(BOOL)force
78 if (_handshakeCompleted && !force) {
82 //Delay if we haven't met the interval time limit
83 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
85 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
86 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
90 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
91 if (!_handshakeCompleted && user) {
92 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
94 [_lastStatus release];
95 _lastStatus = [NSLocalizedString(@"audioscrobbler_handshaking", @"Attempting to handshake with server") retain];
96 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
98 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
99 _responseData = [[NSMutableData alloc] init];
100 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
104 - (BOOL)handshakeCompleted
106 return _handshakeCompleted;
109 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
111 ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
112 NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
116 (album == nil) ? @"" : album,
118 [NSString stringWithFormat:@"%i", length],
120 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
123 [_tracks addObject:newTrack];
129 if (!_handshakeCompleted) {
130 [self attemptHandshake:NO];
134 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
135 char *pass = (char *)[passString UTF8String];
137 if (passString == nil) {
138 ITDebugLog(@"Audioscrobbler: Access denied to user password");
142 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
144 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
145 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
150 NSMutableString *requestString;
151 NSString *authString, *responseHash = @"";
152 unsigned char *buffer;
155 ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
157 if ([_tracks count] == 0) {
158 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
162 //Build the MD5 response string we send along with the request
163 buffer = malloc(EVP_MD_size(EVP_md5()));
164 EVP_DigestInit(&ctx, EVP_md5());
165 EVP_DigestUpdate(&ctx, pass, strlen(pass));
166 EVP_DigestFinal(&ctx, buffer, NULL);
168 for (i = 0; i < 16; i++) {
169 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
173 buffer = malloc(EVP_MD_size(EVP_md5()));
174 char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
175 EVP_DigestInit(&ctx, EVP_md5());
176 EVP_DigestUpdate(&ctx, cat, strlen(cat));
177 EVP_DigestFinal(&ctx, buffer, NULL);
180 for (i = 0; i < 16; i++) {
181 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
185 authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
186 requestString = [[NSMutableString alloc] initWithString:authString];
187 [authString release];
189 //We can only submit ten tracks at a time
190 for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
191 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
192 NSString *artistEscaped, *titleEscaped, *albumEscaped, *timeEscaped, *ampersand = @"&";
194 //Escape each of the individual parameters we're sending
195 artistEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"artist"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
196 titleEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"title"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
197 albumEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"album"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
198 timeEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"time"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
200 [requestString appendString:[NSString stringWithFormat:@"&a[%i]=%@&t[%i]=%@&b[%i]=%@&m[%i]=&l[%i]=%@&i[%i]=%@", i, artistEscaped,
204 i, [nextTrack objectForKey:@"length"],
207 //Release the escaped strings
208 [artistEscaped release];
209 [titleEscaped release];
210 [albumEscaped release];
211 [timeEscaped release];
213 [_submitTracks addObject:nextTrack];
216 ITDebugLog(@"Audioscrobbler: Sending track submission request");
217 [_lastStatus release];
218 _lastStatus = [NSLocalizedString(@"audioscrobbler_submitting", @"Submitting tracks to server") retain];
219 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
221 //Create and send the request
222 NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
223 [request setHTTPMethod:@"POST"];
224 [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
225 _currentStatus = AudioscrobblerSubmittingTracksStatus;
226 _responseData = [[NSMutableData alloc] init];
227 [NSURLConnection connectionWithRequest:request delegate:self];
228 [requestString release];
231 //For now we're not going to cache results, as it is less of a headache
232 //[_tracks removeObjectsInArray:_submitTracks];
233 [_tracks removeAllObjects];
234 [_submitTracks removeAllObjects];
236 //If we have tracks left, submit again after the interval seconds
239 - (void)handleAudioscrobblerNotification:(NSNotification *)note
241 if ([_tracks count] > 0) {
242 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
248 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
250 [_responseData release];
251 [_lastStatus release];
252 _lastStatus = [[NSString stringWithFormat:NSLocalizedString(@"audioscrobbler_error", @"Error - %@"), [error localizedDescription]] retain];
253 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:self userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
254 ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
257 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
259 [_responseData appendData:data];
262 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
264 NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
265 NSArray *lines = [string componentsSeparatedByString:@"\n"];
266 NSString *responseAction = nil, *key = nil, *comment = nil;
268 if ([lines count] > 0) {
269 responseAction = [lines objectAtIndex:0];
271 ITDebugLog(@"Audioscrobbler: Response %@", string);
272 if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
273 if ([lines count] < 2) {
274 //We have a protocol error
276 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
277 if ([lines count] >= 4) {
278 _md5Challenge = [[lines objectAtIndex:1] retain];
279 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
280 _handshakeCompleted = YES;
281 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
282 key = @"audioscrobbler_handshake_complete";
283 comment = @"Handshake complete";
285 //We have a protocol error
287 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
288 ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
289 key = @"audioscrobbler_handshake_failed";
290 comment = @"Handshake failed";
292 } else if ([responseAction isEqualToString:@"BADUSER"]) {
293 ITDebugLog(@"Audioscrobbler: Bad user name");
294 key = @"audioscrobbler_bad_user";
295 comment = @"Handshake failed - invalid user name";
298 ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
299 key = @"audioscrobbler_protocol_error";
300 comment = @"Internal protocol error";
301 //We have a protocol error
303 } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
304 if ([responseAction isEqualToString:@"OK"]) {
305 ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
306 /*[_tracks removeObjectsInArray:_submitTracks];
307 [_submitTracks removeAllObjects];*/
308 if ([_tracks count] > 0) {
309 ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
310 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
312 key = @"audioscrobbler_submission_ok";
313 comment = @"Last track submission successful";
314 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
315 ITDebugLog(@"Audioscrobbler: Bad password");
316 key = @"audioscrobbler_bad_password";
317 comment = @"Last track submission failed - invalid password";
319 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
320 ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
321 key = @"audioscrobbler_submission_failed";
322 comment = @"Last track submission failed - see console for error";
327 //Handle the final INTERVAL response
328 if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
329 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
330 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
331 [_delayDate release];
332 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
334 ITDebugLog(@"No interval response.");
335 //We have a protocol error
337 [_lastStatus release];
338 _lastStatus = [NSLocalizedString(key, comment) retain];
339 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
341 [_responseData release];
344 -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
346 //Don't cache any Audioscrobbler communication