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];
46 _responseData = [[NSMutableData alloc] init];
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 //If we've already tried to handshake three times in a row unsuccessfully, set the attempt count to -3
83 if (_handshakeAttempts > 3) {
84 ITDebugLog(@"Audioscrobbler: Maximum handshake limit reached (3). Retrying when handshake attempts reach zero.");
85 _handshakeAttempts = -3;
87 //Remove any tracks we were trying to submit, just to be safe
88 [_submitTracks removeAllObjects];
93 //Increment the number of times we've tried to handshake
96 //We're still on our self-imposed cooldown time.
97 if (_handshakeAttempts < 0) {
98 ITDebugLog(@"Audioscrobbler: Handshake timeout. Retrying when handshake attempts reach zero.");
102 //Delay if we haven't met the interval time limit
103 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
105 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
106 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
110 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
111 if (!_handshakeCompleted && user) {
112 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
114 [_lastStatus release];
115 _lastStatus = [NSLocalizedString(@"audioscrobbler_handshaking", @"Attempting to handshake with server") retain];
116 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
118 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
119 //_responseData = [[NSMutableData alloc] init];
120 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
124 - (BOOL)handshakeCompleted
126 return _handshakeCompleted;
129 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
131 ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
132 NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
136 (album == nil) ? @"" : album,
138 [NSString stringWithFormat:@"%i", length],
140 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
143 [_tracks addObject:newTrack];
149 if (!_handshakeCompleted) {
150 [self attemptHandshake:NO];
154 ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
156 if ([_tracks count] == 0) {
157 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
161 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
162 char *pass = (char *)[passString UTF8String];
164 if (passString == nil) {
165 ITDebugLog(@"Audioscrobbler: Access denied to user password");
169 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
171 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
172 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
177 NSMutableString *requestString;
178 NSString *authString, *responseHash = @"";
179 unsigned char *buffer;
182 //Build the MD5 response string we send along with the request
183 buffer = malloc(EVP_MD_size(EVP_md5()));
184 EVP_DigestInit(&ctx, EVP_md5());
185 EVP_DigestUpdate(&ctx, pass, strlen(pass));
186 EVP_DigestFinal(&ctx, buffer, NULL);
188 for (i = 0; i < 16; i++) {
189 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
193 buffer = malloc(EVP_MD_size(EVP_md5()));
194 char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
195 EVP_DigestInit(&ctx, EVP_md5());
196 EVP_DigestUpdate(&ctx, cat, strlen(cat));
197 EVP_DigestFinal(&ctx, buffer, NULL);
200 for (i = 0; i < 16; i++) {
201 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
205 authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
206 requestString = [[NSMutableString alloc] initWithString:authString];
207 [authString release];
209 //We can only submit ten tracks at a time
210 for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
211 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
212 NSString *artistEscaped, *titleEscaped, *albumEscaped, *timeEscaped, *ampersand = @"&";
214 //Escape each of the individual parameters we're sending
215 artistEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"artist"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
216 titleEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"title"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
217 albumEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"album"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
218 timeEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"time"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
220 [requestString appendString:[NSString stringWithFormat:@"&a[%i]=%@&t[%i]=%@&b[%i]=%@&m[%i]=&l[%i]=%@&i[%i]=%@", i, artistEscaped,
224 i, [nextTrack objectForKey:@"length"],
227 //Release the escaped strings
228 [artistEscaped release];
229 [titleEscaped release];
230 [albumEscaped release];
231 [timeEscaped release];
233 [_submitTracks addObject:nextTrack];
236 ITDebugLog(@"Audioscrobbler: Sending track submission request");
237 [_lastStatus release];
238 _lastStatus = [NSLocalizedString(@"audioscrobbler_submitting", @"Submitting tracks to server") retain];
239 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
241 //Create and send the request
242 NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
243 [request setHTTPMethod:@"POST"];
244 [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
245 _currentStatus = AudioscrobblerSubmittingTracksStatus;
246 //_responseData = [[NSMutableData alloc] init];
247 [_responseData setData:nil];
248 [NSURLConnection connectionWithRequest:request delegate:self];
249 [requestString release];
252 //For now we're not going to cache results, as it is less of a headache
253 //[_tracks removeObjectsInArray:_submitTracks];
254 [_tracks removeAllObjects];
255 //[_submitTracks removeAllObjects];
257 //If we have tracks left, submit again after the interval seconds
260 - (void)handleAudioscrobblerNotification:(NSNotification *)note
262 if ([_tracks count] > 0) {
263 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
269 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
271 [_responseData setData:nil];
272 [_lastStatus release];
273 _lastStatus = [[NSString stringWithFormat:NSLocalizedString(@"audioscrobbler_error", @"Error - %@"), [error localizedDescription]] retain];
274 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:self userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
275 ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
278 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
280 [_responseData appendData:data];
283 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
285 NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
286 NSArray *lines = [string componentsSeparatedByString:@"\n"];
287 NSString *responseAction = nil, *key = nil, *comment = nil;
289 if ([lines count] > 0) {
290 responseAction = [lines objectAtIndex:0];
292 ITDebugLog(@"Audioscrobbler: Response %@", string);
293 if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
294 if ([lines count] < 2) {
295 //We have a protocol error
297 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
298 if ([lines count] >= 4) {
299 _md5Challenge = [[lines objectAtIndex:1] retain];
300 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
301 _handshakeCompleted = YES;
302 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
303 key = @"audioscrobbler_handshake_complete";
304 comment = @"Handshake complete";
305 _handshakeAttempts = 0;
307 //We have a protocol error
309 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
310 ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
311 key = @"audioscrobbler_handshake_failed";
312 comment = @"Handshake failed";
314 } else if ([responseAction isEqualToString:@"BADUSER"]) {
315 ITDebugLog(@"Audioscrobbler: Bad user name");
316 key = @"audioscrobbler_bad_user";
317 comment = @"Handshake failed - invalid user name";
320 //Don't count this as a bad handshake attempt
321 _handshakeAttempts = 0;
323 ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
324 key = @"audioscrobbler_protocol_error";
325 comment = @"Internal protocol error";
326 //We have a protocol error
328 } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
329 if ([responseAction isEqualToString:@"OK"]) {
330 ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
331 /*[_tracks removeObjectsInArray:_submitTracks];
332 [_submitTracks removeAllObjects];*/
333 [_submitTracks removeAllObjects];
334 if ([_tracks count] > 0) {
335 ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
336 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
338 key = @"audioscrobbler_submission_ok";
339 comment = @"Last track submission successful";
340 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
341 ITDebugLog(@"Audioscrobbler: Bad password");
342 key = @"audioscrobbler_bad_password";
343 comment = @"Last track submission failed - invalid password";
346 //Add the tracks we were trying to submit back into the submission queue
347 [_tracks addObjectsFromArray:_submitTracks];
349 _handshakeCompleted = NO;
351 //If we were previously valid with the same login name, try reauthenticating and sending again
352 [self attemptHandshake:YES];
353 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
354 ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
355 key = @"audioscrobbler_submission_failed";
356 comment = @"Last track submission failed - see console for error";
359 //We got an unknown error. To be safe we're going to remove the tracks we tried to submit
360 [_submitTracks removeAllObjects];
362 _handshakeCompleted = NO;
366 //Handle the final INTERVAL response
367 if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
368 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
369 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
370 [_delayDate release];
371 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
373 ITDebugLog(@"No interval response.");
374 //We have a protocol error
376 [_lastStatus release];
377 _lastStatus = [NSLocalizedString(key, comment) retain];
378 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
380 [_responseData setData:nil];
383 -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
385 //Don't cache any Audioscrobbler communication