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/"];*/
54 _delayDate = [[NSDate date] retain];
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];
74 - (void)attemptHandshake
76 [self attemptHandshake:NO];
79 - (void)attemptHandshake:(BOOL)force
81 if (_handshakeCompleted && !force) {
85 //Delay if we haven't met the interval time limit
86 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
88 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
89 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
93 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
94 if (!_handshakeCompleted && user) {
95 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
97 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
98 _responseData = [[NSMutableData alloc] init];
99 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
103 - (BOOL)handshakeCompleted
105 return _handshakeCompleted;
108 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
110 ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
111 NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
115 (album == nil) ? @"" : album,
117 [NSString stringWithFormat:@"%i", length],
119 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
122 [_tracks addObject:newTrack];
128 if (!_handshakeCompleted) {
129 [self attemptHandshake:NO];
133 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
134 char *pass = (char *)[passString UTF8String];
136 if (passString == nil) {
137 ITDebugLog(@"Audioscrobbler: Access denied to user password");
141 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
143 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
144 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
149 NSMutableString *requestString;
150 NSString *authString, *responseHash = @"";
151 unsigned char *buffer;
154 ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
156 if ([_tracks count] == 0) {
157 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
161 //Build the MD5 response string we send along with the request
162 buffer = malloc(EVP_MD_size(EVP_md5()));
163 EVP_DigestInit(&ctx, EVP_md5());
164 EVP_DigestUpdate(&ctx, pass, strlen(pass));
165 EVP_DigestFinal(&ctx, buffer, NULL);
167 for (i = 0; i < 16; i++) {
168 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
172 buffer = malloc(EVP_MD_size(EVP_md5()));
173 char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
174 EVP_DigestInit(&ctx, EVP_md5());
175 EVP_DigestUpdate(&ctx, cat, strlen(cat));
176 EVP_DigestFinal(&ctx, buffer, NULL);
179 for (i = 0; i < 16; i++) {
180 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
184 authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
185 requestString = [[NSMutableString alloc] initWithString:authString];
186 [authString release];
188 //We can only submit ten tracks at a time
189 for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
190 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
191 NSString *trackString;
193 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);
194 [requestString appendString:trackString];
195 [trackString release];
196 [_submitTracks addObject:nextTrack];
199 ITDebugLog(@"Audioscrobbler: Sending track submission request");
201 //Create and send the request
202 NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
203 [request setHTTPMethod:@"POST"];
204 [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
205 _currentStatus = AudioscrobblerSubmittingTracksStatus;
206 _responseData = [[NSMutableData alloc] init];
207 [NSURLConnection connectionWithRequest:request delegate:self];
208 [requestString release];
211 //If we have tracks left, submit again after the interval seconds
214 - (void)handleAudioscrobblerNotification:(NSNotification *)note
216 if ([[note name] isEqualToString:@"AudioscrobblerHandshakeComplete"]) {
217 if ([_tracks count] > 0) {
218 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
225 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
227 ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
230 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
232 [_responseData appendData:data];
235 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
237 NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
238 NSArray *lines = [string componentsSeparatedByString:@"\n"];
239 NSString *responseAction = nil;
241 if ([lines count] > 0) {
242 responseAction = [lines objectAtIndex:0];
244 ITDebugLog(@"Audioscrobbler: Response %@", string);
245 if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
246 if ([lines count] < 2) {
247 //We have a protocol error
249 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
250 if ([lines count] >= 4) {
251 _md5Challenge = [[lines objectAtIndex:1] retain];
252 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
253 _handshakeCompleted = YES;
254 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
256 //We have a protocol error
258 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
259 ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
261 } else if ([responseAction isEqualToString:@"BADUSER"]) {
262 ITDebugLog(@"Audioscrobbler: Bad user name");
265 ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
266 //We have a protocol error
268 } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
269 if ([responseAction isEqualToString:@"OK"]) {
270 ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
271 [_tracks removeObjectsInArray:_submitTracks];
272 [_submitTracks removeAllObjects];
273 if ([_tracks count] > 0) {
274 ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
275 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
277 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
278 ITDebugLog(@"Audioscrobbler: Bad password");
280 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
281 ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
286 //Handle the final INTERVAL response
287 if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
288 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
289 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
290 [_delayDate release];
291 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
293 ITDebugLog(@"No interval response.");
294 //We have a protocol error
298 [_responseData release];