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 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
95 _responseData = [[NSMutableData alloc] init];
96 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
100 - (BOOL)handshakeCompleted
102 return _handshakeCompleted;
105 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
107 ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
108 NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
112 (album == nil) ? @"" : album,
114 [NSString stringWithFormat:@"%i", length],
116 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
119 [_tracks addObject:newTrack];
125 if (!_handshakeCompleted) {
126 [self attemptHandshake:NO];
130 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
131 char *pass = (char *)[passString UTF8String];
133 if (passString == nil) {
134 ITDebugLog(@"Audioscrobbler: Access denied to user password");
138 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
140 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
141 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
146 NSMutableString *requestString;
147 NSString *authString, *responseHash = @"";
148 unsigned char *buffer;
151 ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
153 if ([_tracks count] == 0) {
154 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
158 //Build the MD5 response string we send along with the request
159 buffer = malloc(EVP_MD_size(EVP_md5()));
160 EVP_DigestInit(&ctx, EVP_md5());
161 EVP_DigestUpdate(&ctx, pass, strlen(pass));
162 EVP_DigestFinal(&ctx, buffer, NULL);
164 for (i = 0; i < 16; i++) {
165 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
169 buffer = malloc(EVP_MD_size(EVP_md5()));
170 char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
171 EVP_DigestInit(&ctx, EVP_md5());
172 EVP_DigestUpdate(&ctx, cat, strlen(cat));
173 EVP_DigestFinal(&ctx, buffer, NULL);
176 for (i = 0; i < 16; i++) {
177 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
181 authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
182 requestString = [[NSMutableString alloc] initWithString:authString];
183 [authString release];
185 //We can only submit ten tracks at a time
186 for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
187 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
188 NSString *artistEscaped, *titleEscaped, *albumEscaped, *timeEscaped, *ampersand = @"&";
190 //Escape each of the individual parameters we're sending
191 artistEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"artist"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
192 titleEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"title"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
193 albumEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"album"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
194 timeEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"time"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
196 [requestString appendString:[NSString stringWithFormat:@"&a[%i]=%@&t[%i]=%@&b[%i]=%@&m[%i]=&l[%i]=%@&i[%i]=%@", i, artistEscaped,
200 i, [nextTrack objectForKey:@"length"],
203 //Release the escaped strings
204 [artistEscaped release];
205 [titleEscaped release];
206 [albumEscaped release];
207 [timeEscaped release];
209 [_submitTracks addObject:nextTrack];
212 ITDebugLog(@"Audioscrobbler: Sending track submission request");
214 //Create and send the request
215 NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
216 NSLog(@"Posting Audioscrobbler URL request: %@", requestString);
217 [request setHTTPMethod:@"POST"];
218 [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
219 _currentStatus = AudioscrobblerSubmittingTracksStatus;
220 _responseData = [[NSMutableData alloc] init];
221 [NSURLConnection connectionWithRequest:request delegate:self];
222 [requestString release];
225 //If we have tracks left, submit again after the interval seconds
228 - (void)handleAudioscrobblerNotification:(NSNotification *)note
230 if ([_tracks count] > 0) {
231 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
237 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
239 [_lastStatus release];
240 _lastStatus = [[NSString stringWithFormat:NSLocalizedString(@"audioscrobbler_error", @"Error - %@"), [error localizedDescription]] retain];
241 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:self userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
242 ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
245 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
247 [_responseData appendData:data];
250 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
252 NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
253 NSArray *lines = [string componentsSeparatedByString:@"\n"];
254 NSString *responseAction = nil, *key = nil, *comment = nil;
256 if ([lines count] > 0) {
257 responseAction = [lines objectAtIndex:0];
259 ITDebugLog(@"Audioscrobbler: Response %@", string);
260 NSLog(@"Audioscrobbler: Response %@", string);
261 if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
262 if ([lines count] < 2) {
263 //We have a protocol error
265 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
266 if ([lines count] >= 4) {
267 _md5Challenge = [[lines objectAtIndex:1] retain];
268 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
269 _handshakeCompleted = YES;
270 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
271 key = @"audioscrobbler_handshake_complete";
272 comment = @"Handshake complete";
274 //We have a protocol error
276 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
277 ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
278 key = @"audioscrobbler_handshake_failed";
279 comment = @"Handshake failed";
281 } else if ([responseAction isEqualToString:@"BADUSER"]) {
282 ITDebugLog(@"Audioscrobbler: Bad user name");
283 key = @"audioscrobbler_bad_user";
284 comment = @"Handshake failed - invalid user name";
287 ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
288 key = @"audioscrobbler_protocol_error";
289 comment = @"Internal protocol error";
290 //We have a protocol error
292 } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
293 //For now we're not going to cache results, as it is less of a headache
294 [_tracks removeObjectsInArray:_submitTracks];
295 [_submitTracks removeAllObjects];
297 if ([responseAction isEqualToString:@"OK"]) {
298 ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
299 /*[_tracks removeObjectsInArray:_submitTracks];
300 [_submitTracks removeAllObjects];*/
301 if ([_tracks count] > 0) {
302 ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
303 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
305 key = @"audioscrobbler_submission_ok";
306 comment = @"Last track submission successful";
307 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
308 ITDebugLog(@"Audioscrobbler: Bad password");
309 key = @"audioscrobbler_bad_password";
310 comment = @"Last track submission failed - invalid password";
312 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
313 ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
314 NSLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
315 key = @"audioscrobbler_submission_failed";
316 comment = @"Last track submission failed - see console for error";
321 //Handle the final INTERVAL response
322 if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
323 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
324 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
325 [_delayDate release];
326 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
328 ITDebugLog(@"No interval response.");
329 //We have a protocol error
331 [_lastStatus release];
332 _lastStatus = [NSLocalizedString(key, comment) retain];
333 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
335 [_responseData release];