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 //For now we're not going to cache results, as it is less of a headache
226 //[_tracks removeObjectsInArray:_submitTracks];
227 [_tracks removeAllObjects];
228 [_submitTracks removeAllObjects];
230 //If we have tracks left, submit again after the interval seconds
233 - (void)handleAudioscrobblerNotification:(NSNotification *)note
235 if ([_tracks count] > 0) {
236 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
242 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
244 [_responseData release];
245 [_lastStatus release];
246 _lastStatus = [[NSString stringWithFormat:NSLocalizedString(@"audioscrobbler_error", @"Error - %@"), [error localizedDescription]] retain];
247 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:self userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
248 ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
251 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
253 [_responseData appendData:data];
256 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
258 NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
259 NSArray *lines = [string componentsSeparatedByString:@"\n"];
260 NSString *responseAction = nil, *key = nil, *comment = nil;
262 if ([lines count] > 0) {
263 responseAction = [lines objectAtIndex:0];
265 ITDebugLog(@"Audioscrobbler: Response %@", string);
266 NSLog(@"Audioscrobbler: Response %@", string);
267 if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
268 if ([lines count] < 2) {
269 //We have a protocol error
271 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
272 if ([lines count] >= 4) {
273 _md5Challenge = [[lines objectAtIndex:1] retain];
274 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
275 _handshakeCompleted = YES;
276 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
277 key = @"audioscrobbler_handshake_complete";
278 comment = @"Handshake complete";
280 //We have a protocol error
282 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
283 ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
284 key = @"audioscrobbler_handshake_failed";
285 comment = @"Handshake failed";
287 } else if ([responseAction isEqualToString:@"BADUSER"]) {
288 ITDebugLog(@"Audioscrobbler: Bad user name");
289 key = @"audioscrobbler_bad_user";
290 comment = @"Handshake failed - invalid user name";
293 ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
294 key = @"audioscrobbler_protocol_error";
295 comment = @"Internal protocol error";
296 //We have a protocol error
298 } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
299 if ([responseAction isEqualToString:@"OK"]) {
300 ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
301 /*[_tracks removeObjectsInArray:_submitTracks];
302 [_submitTracks removeAllObjects];*/
303 if ([_tracks count] > 0) {
304 ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
305 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
307 key = @"audioscrobbler_submission_ok";
308 comment = @"Last track submission successful";
309 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
310 ITDebugLog(@"Audioscrobbler: Bad password");
311 key = @"audioscrobbler_bad_password";
312 comment = @"Last track submission failed - invalid password";
314 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
315 ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
316 NSLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
317 key = @"audioscrobbler_submission_failed";
318 comment = @"Last track submission failed - see console for error";
323 //Handle the final INTERVAL response
324 if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
325 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
326 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
327 [_delayDate release];
328 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
330 ITDebugLog(@"No interval response.");
331 //We have a protocol error
333 [_lastStatus release];
334 _lastStatus = [NSLocalizedString(key, comment) retain];
335 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
337 [_responseData release];