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
28 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
29 [[AudioscrobblerController sharedController] submitTrack:@"Immigrant Song" artist:@"Led Zeppelin" album:@"How The West Was Won" length:221];
30 [[AudioscrobblerController sharedController] submitTrack:@"Comfortably Numb" artist:@"Pink Floyd" album:@"The Wall" length:384];
31 [[AudioscrobblerController sharedController] submitTracks];
35 + (AudioscrobblerController *)sharedController
37 if (!_sharedController) {
38 _sharedController = [[AudioscrobblerController alloc] init];
40 return _sharedController;
45 if ( (self = [super init]) ) {
46 _handshakeCompleted = NO;
50 /*_handshakeCompleted = YES;
51 _md5Challenge = @"rawr";
52 _postURL = [NSURL URLWithString:@"http://audioscrobbler.com/"];*/
56 _tracks = [[NSMutableArray alloc] init];
57 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioscrobblerNotification:) name:nil object:self];
64 [_md5Challenge release];
66 [_responseData release];
71 - (void)attemptHandshake:(BOOL)force
73 if (_handshakeCompleted && !force) {
77 //Delay if we haven't met the interval time limit
78 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
80 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
81 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
85 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
86 if (!_handshakeCompleted && user) {
87 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
89 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
90 _responseData = [[NSMutableData alloc] init];
91 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
95 - (BOOL)handshakeCompleted
97 return _handshakeCompleted;
100 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
102 ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
103 NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
107 (album == nil) ? @"" : album,
109 [NSString stringWithFormat:@"%i", length],
111 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
114 [_tracks addObject:newTrack];
120 if (!_handshakeCompleted) {
121 [self attemptHandshake:NO];
125 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
126 char *pass = (char *)[passString UTF8String];
128 if (passString == nil) {
129 NSLog(@"Audioscrobbler: Access denied to user password");
133 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
135 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
136 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
141 NSMutableString *requestString;
142 NSString *authString, *responseHash = @"";
143 unsigned char *buffer;
146 ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
148 if ([_tracks count] == 0) {
149 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
153 //Build the MD5 response string we send along with the request
154 buffer = malloc(EVP_MD_size(EVP_md5()));
155 EVP_DigestInit(&ctx, EVP_md5());
156 EVP_DigestUpdate(&ctx, pass, strlen(pass));
157 EVP_DigestFinal(&ctx, buffer, NULL);
159 for (i = 0; i < 16; i++) {
160 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
164 buffer = malloc(EVP_MD_size(EVP_md5()));
165 char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
166 EVP_DigestInit(&ctx, EVP_md5());
167 EVP_DigestUpdate(&ctx, cat, strlen(cat));
168 EVP_DigestFinal(&ctx, buffer, NULL);
171 for (i = 0; i < 16; i++) {
172 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
176 authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
177 requestString = [[NSMutableString alloc] initWithString:authString];
178 [authString release];
180 //We can only submit ten tracks at a time
181 for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
182 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
183 NSString *trackString;
185 trackString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"&a[%i]=%@&t[%i]=%@&b[%i]=%@&m[%i]=&l[%i]=%@&i[%i]=%@", i, [nextTrack objectForKey:@"artist"], i, [nextTrack objectForKey:@"title"], i, [nextTrack objectForKey:@"album"], i, i, [nextTrack objectForKey:@"length"], i, [nextTrack objectForKey:@"time"]], NULL, NULL, kCFStringEncodingUTF8);
186 [requestString appendString:trackString];
187 [trackString release];
190 //Create and send the request
191 NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
192 [request setHTTPMethod:@"POST"];
193 [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
194 _currentStatus = AudioscrobblerSubmittingTracksStatus;
195 _responseData = [[NSMutableData alloc] init];
196 [NSURLConnection connectionWithRequest:request delegate:self];
197 [requestString release];
200 //If we have tracks left, submit again after the interval seconds
203 - (void)handleAudioscrobblerNotification:(NSNotification *)note
205 if ([[note name] isEqualToString:@"AudioscrobblerHandshakeComplete"]) {
206 if ([_tracks count] > 0) {
207 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
214 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
216 ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
219 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
221 [_responseData appendData:data];
224 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
226 NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
227 NSArray *lines = [string componentsSeparatedByString:@"\n"];
228 NSString *responseAction = nil;
230 if ([lines count] > 0) {
231 responseAction = [lines objectAtIndex:0];
234 if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
235 if ([lines count] < 2) {
236 //We have a protocol error
238 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
239 if ([lines count] >= 4) {
240 _md5Challenge = [[lines objectAtIndex:1] retain];
241 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
242 _handshakeCompleted = YES;
243 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
245 //We have a protocol error
247 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
249 } else if ([responseAction isEqualToString:@"BADUSER"]) {
252 //We have a protocol error
254 } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
255 if ([responseAction isEqualToString:@"OK"]) {
256 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
258 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
263 //Handle the final INTERVAL response
264 if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
265 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
266 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
267 [_delayDate release];
268 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
270 ITDebugLog(@"No interval response.");
271 //We have a protocol error
275 [_responseData release];