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 @"tst"
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:nil object:self];
56 [_md5Challenge release];
58 [_responseData release];
59 [_submitTracks release];
65 - (void)attemptHandshake
67 [self attemptHandshake:NO];
70 - (void)attemptHandshake:(BOOL)force
72 if (_handshakeCompleted && !force) {
76 //Delay if we haven't met the interval time limit
77 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
79 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
80 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
84 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
85 if (!_handshakeCompleted && user) {
86 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
88 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
89 _responseData = [[NSMutableData alloc] init];
90 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
94 - (BOOL)handshakeCompleted
96 return _handshakeCompleted;
99 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
101 ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
102 NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
106 (album == nil) ? @"" : album,
108 [NSString stringWithFormat:@"%i", length],
110 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
113 [_tracks addObject:newTrack];
119 if (!_handshakeCompleted) {
120 [self attemptHandshake:NO];
124 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
125 char *pass = (char *)[passString UTF8String];
127 if (passString == nil) {
128 ITDebugLog(@"Audioscrobbler: Access denied to user password");
132 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
134 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
135 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
140 NSMutableString *requestString;
141 NSString *authString, *responseHash = @"";
142 unsigned char *buffer;
145 ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
147 if ([_tracks count] == 0) {
148 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
152 //Build the MD5 response string we send along with the request
153 buffer = malloc(EVP_MD_size(EVP_md5()));
154 EVP_DigestInit(&ctx, EVP_md5());
155 EVP_DigestUpdate(&ctx, pass, strlen(pass));
156 EVP_DigestFinal(&ctx, buffer, NULL);
158 for (i = 0; i < 16; i++) {
159 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
163 buffer = malloc(EVP_MD_size(EVP_md5()));
164 char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
165 EVP_DigestInit(&ctx, EVP_md5());
166 EVP_DigestUpdate(&ctx, cat, strlen(cat));
167 EVP_DigestFinal(&ctx, buffer, NULL);
170 for (i = 0; i < 16; i++) {
171 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
175 authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
176 requestString = [[NSMutableString alloc] initWithString:authString];
177 [authString release];
179 //We can only submit ten tracks at a time
180 for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
181 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
182 NSString *artistEscaped, *titleEscaped, *albumEscaped, *timeEscaped, *ampersand = @"&";
184 //Escape each of the individual parameters we're sending
185 artistEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"artist"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
186 titleEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"title"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
187 albumEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"album"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
188 timeEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"time"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
190 [requestString appendString:[NSString stringWithFormat:@"&a[%i]=%@&t[%i]=%@&b[%i]=%@&m[%i]=&l[%i]=%@&i[%i]=%@", i, artistEscaped,
194 i, [nextTrack objectForKey:@"length"],
197 //Release the escaped strings
198 [artistEscaped release];
199 [titleEscaped release];
200 [albumEscaped release];
201 [timeEscaped release];
203 [_submitTracks addObject:nextTrack];
206 ITDebugLog(@"Audioscrobbler: Sending track submission request");
208 //Create and send the request
209 NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
210 NSLog(@"Posting Audioscrobbler URL request: %@", requestString);
211 [request setHTTPMethod:@"POST"];
212 [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
213 _currentStatus = AudioscrobblerSubmittingTracksStatus;
214 _responseData = [[NSMutableData alloc] init];
215 [NSURLConnection connectionWithRequest:request delegate:self];
216 [requestString release];
219 //If we have tracks left, submit again after the interval seconds
222 - (void)handleAudioscrobblerNotification:(NSNotification *)note
224 if ([[note name] isEqualToString:@"AudioscrobblerHandshakeComplete"]) {
225 if ([_tracks count] > 0) {
226 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
233 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
235 ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
238 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
240 [_responseData appendData:data];
243 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
245 NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
246 NSArray *lines = [string componentsSeparatedByString:@"\n"];
247 NSString *responseAction = nil;
249 if ([lines count] > 0) {
250 responseAction = [lines objectAtIndex:0];
252 ITDebugLog(@"Audioscrobbler: Response %@", string);
253 NSLog(@"Audioscrobbler: Response %@", string);
254 if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
255 if ([lines count] < 2) {
256 //We have a protocol error
258 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
259 if ([lines count] >= 4) {
260 _md5Challenge = [[lines objectAtIndex:1] retain];
261 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
262 _handshakeCompleted = YES;
263 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
265 //We have a protocol error
267 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
268 ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
270 } else if ([responseAction isEqualToString:@"BADUSER"]) {
271 ITDebugLog(@"Audioscrobbler: Bad user name");
274 ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
275 //We have a protocol error
277 } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
278 if ([responseAction isEqualToString:@"OK"]) {
279 ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
280 [_tracks removeObjectsInArray:_submitTracks];
281 [_submitTracks removeAllObjects];
282 if ([_tracks count] > 0) {
283 ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
284 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
286 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
287 ITDebugLog(@"Audioscrobbler: Bad password");
289 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
290 ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
295 //Handle the final INTERVAL response
296 if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
297 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
298 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
299 [_delayDate release];
300 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
302 ITDebugLog(@"No interval response.");
303 //We have a protocol error
307 [_responseData release];