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 _submitTracks = [[NSMutableArray alloc] init];
58 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioscrobblerNotification:) name:nil object:self];
65 [_md5Challenge release];
67 [_responseData release];
68 [_submitTracks release];
73 - (void)attemptHandshake:(BOOL)force
75 if (_handshakeCompleted && !force) {
79 //Delay if we haven't met the interval time limit
80 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
82 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
83 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
87 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
88 if (!_handshakeCompleted && user) {
89 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
91 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
92 _responseData = [[NSMutableData alloc] init];
93 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
97 - (BOOL)handshakeCompleted
99 return _handshakeCompleted;
102 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
104 ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
105 NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
109 (album == nil) ? @"" : album,
111 [NSString stringWithFormat:@"%i", length],
113 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
116 [_tracks addObject:newTrack];
122 if (!_handshakeCompleted) {
123 [self attemptHandshake:NO];
127 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
128 char *pass = (char *)[passString UTF8String];
130 if (passString == nil) {
131 NSLog(@"Audioscrobbler: Access denied to user password");
135 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
137 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
138 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
143 NSMutableString *requestString;
144 NSString *authString, *responseHash = @"";
145 unsigned char *buffer;
148 ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
150 if ([_tracks count] == 0) {
151 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
155 //Build the MD5 response string we send along with the request
156 buffer = malloc(EVP_MD_size(EVP_md5()));
157 EVP_DigestInit(&ctx, EVP_md5());
158 EVP_DigestUpdate(&ctx, pass, strlen(pass));
159 EVP_DigestFinal(&ctx, buffer, NULL);
161 for (i = 0; i < 16; i++) {
162 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
166 buffer = malloc(EVP_MD_size(EVP_md5()));
167 char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
168 EVP_DigestInit(&ctx, EVP_md5());
169 EVP_DigestUpdate(&ctx, cat, strlen(cat));
170 EVP_DigestFinal(&ctx, buffer, NULL);
173 for (i = 0; i < 16; i++) {
174 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
178 authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
179 requestString = [[NSMutableString alloc] initWithString:authString];
180 [authString release];
182 //We can only submit ten tracks at a time
183 for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
184 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
185 NSString *trackString;
187 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);
188 [requestString appendString:trackString];
189 [trackString release];
190 [_submitTracks addObject:nextTrack];
193 //Create and send the request
194 NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
195 [request setHTTPMethod:@"POST"];
196 [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
197 _currentStatus = AudioscrobblerSubmittingTracksStatus;
198 _responseData = [[NSMutableData alloc] init];
199 [NSURLConnection connectionWithRequest:request delegate:self];
200 [requestString release];
203 //If we have tracks left, submit again after the interval seconds
206 - (void)handleAudioscrobblerNotification:(NSNotification *)note
208 if ([[note name] isEqualToString:@"AudioscrobblerHandshakeComplete"]) {
209 if ([_tracks count] > 0) {
210 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
217 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
219 ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
222 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
224 [_responseData appendData:data];
227 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
229 NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
230 NSArray *lines = [string componentsSeparatedByString:@"\n"];
231 NSString *responseAction = nil;
233 if ([lines count] > 0) {
234 responseAction = [lines objectAtIndex:0];
237 if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
238 if ([lines count] < 2) {
239 //We have a protocol error
241 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
242 if ([lines count] >= 4) {
243 _md5Challenge = [[lines objectAtIndex:1] retain];
244 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
245 _handshakeCompleted = YES;
246 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
248 //We have a protocol error
250 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
252 } else if ([responseAction isEqualToString:@"BADUSER"]) {
255 //We have a protocol error
257 } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
258 if ([responseAction isEqualToString:@"OK"]) {
259 [_tracks removeObjectsInArray:_submitTracks];
260 [_submitTracks removeAllObjects];
261 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
263 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
268 //Handle the final INTERVAL response
269 if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
270 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
271 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
272 [_delayDate release];
273 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
275 ITDebugLog(@"No interval response.");
276 //We have a protocol error
280 [_responseData release];