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 static AudioscrobblerController *_sharedController = nil;
21 @implementation AudioscrobblerController
25 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
26 [[AudioscrobblerController sharedController] submitTrack:@"Immigrant Song" artist:@"Led Zeppelin" album:@"How The West Was Won" length:221];
27 [[AudioscrobblerController sharedController] submitTrack:@"Comfortably Numb" artist:@"Pink Floyd" album:@"The Wall" length:384];
28 [[AudioscrobblerController sharedController] submitTracks];
32 + (AudioscrobblerController *)sharedController
34 if (!_sharedController) {
35 _sharedController = [[AudioscrobblerController alloc] init];
37 return _sharedController;
42 if ( (self = [super init]) ) {
43 _handshakeCompleted = NO;
47 /*_handshakeCompleted = YES;
48 _md5Challenge = @"rawr";
49 _postURL = [NSURL URLWithString:@"http://audioscrobbler.com/"];*/
53 _tracks = [[NSMutableArray alloc] init];
54 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioscrobblerNotification:) name:nil object:self];
61 [_md5Challenge release];
63 [_responseData release];
68 - (void)attemptHandshake
70 //Delay if we haven't met the interval time limit
71 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
73 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
74 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
78 if (!_handshakeCompleted) {
79 NSString *version = [[[NSBundle bundleWithPath:[[NSWorkspace sharedWorkspace] fullPathForApplication:@"iTunes.app"]] infoDictionary] objectForKey:@"CFBundleVersion"], *user = @"Tristrex";
80 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=tst&v=%@&u=%@", version, user]];
82 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
83 _responseData = [[NSMutableData alloc] init];
84 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30] delegate:self];
88 - (BOOL)handshakeCompleted
90 return _handshakeCompleted;
93 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
95 ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
96 NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
100 (album == nil) ? @"" : album,
102 [NSString stringWithFormat:@"%i", length],
104 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
107 [_tracks addObject:newTrack];
113 if (!_handshakeCompleted) {
114 [self attemptHandshake];
118 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
120 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
121 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
126 NSMutableString *requestString;
127 NSString *authString, *responseHash = @"";
128 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
129 char *pass = (char *)[[PreferencesController getKeychainItemPasswordForUser:user] UTF8String];
130 unsigned char *buffer;
133 ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
135 if ([_tracks count] == 0) {
136 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
140 //Build the MD5 response string we send along with the request
141 buffer = malloc(EVP_MD_size(EVP_md5()));
142 EVP_DigestInit(&ctx, EVP_md5());
143 EVP_DigestUpdate(&ctx, pass, strlen(pass));
144 EVP_DigestFinal(&ctx, buffer, NULL);
146 for (i = 0; i < 16; i++) {
147 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
151 buffer = malloc(EVP_MD_size(EVP_md5()));
152 char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
153 EVP_DigestInit(&ctx, EVP_md5());
154 EVP_DigestUpdate(&ctx, cat, strlen(cat));
155 EVP_DigestFinal(&ctx, buffer, NULL);
158 for (i = 0; i < 16; i++) {
159 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
163 authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
164 requestString = [[NSMutableString alloc] initWithString:authString];
165 [authString release];
167 //We can only submit ten tracks at a time
168 for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
169 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
170 NSString *trackString;
172 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);
173 [requestString appendString:trackString];
174 [trackString release];
177 //Create and send the request
178 NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30] mutableCopy];
179 [request setHTTPMethod:@"POST"];
180 [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
181 _currentStatus = AudioscrobblerSubmittingTracksStatus;
182 _responseData = [[NSMutableData alloc] init];
183 [NSURLConnection connectionWithRequest:request delegate:self];
184 [requestString release];
187 //If we have tracks left, submit again after the interval seconds
190 - (void)handleAudioscrobblerNotification:(NSNotification *)note
192 if ([[note name] isEqualToString:@"AudioscrobblerHandshakeComplete"]) {
193 if ([_tracks count] > 0) {
194 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
201 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
203 ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
206 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
208 [_responseData appendData:data];
211 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
213 NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
214 NSArray *lines = [string componentsSeparatedByString:@"\n"];
215 NSString *responseAction = nil;
217 if ([lines count] > 0) {
218 responseAction = [lines objectAtIndex:0];
221 if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
222 if ([lines count] < 2) {
223 //We have a protocol error
225 if ([responseAction isEqualToString:@"UPTODATE"]) {
226 if ([lines count] >= 4) {
227 _md5Challenge = [[lines objectAtIndex:1] retain];
228 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
229 _handshakeCompleted = YES;
230 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
232 //We have a protocol error
235 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"]) {
236 //Something plus update action
237 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
239 } else if ([responseAction isEqualToString:@"BADUSER"]) {
244 } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
245 if ([responseAction isEqualToString:@"OK"]) {
246 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
248 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
253 //Handle the final INTERVAL response
254 if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
255 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
256 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
257 [_delayDate release];
258 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
260 ITDebugLog(@"No interval response.");
261 //We have a protocol error
265 [_responseData release];