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
73 //Delay if we haven't met the interval time limit
74 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
76 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
77 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
81 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
82 if (!_handshakeCompleted && user) {
83 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
85 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
86 _responseData = [[NSMutableData alloc] init];
87 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30] delegate:self];
91 - (BOOL)handshakeCompleted
93 return _handshakeCompleted;
96 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
98 ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
99 NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
103 (album == nil) ? @"" : album,
105 [NSString stringWithFormat:@"%i", length],
107 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
110 [_tracks addObject:newTrack];
116 if (!_handshakeCompleted) {
117 [self attemptHandshake];
121 NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
123 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
124 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
129 NSMutableString *requestString;
130 NSString *authString, *responseHash = @"";
131 NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
132 char *pass = (char *)[[PreferencesController getKeychainItemPasswordForUser:user] UTF8String];
133 unsigned char *buffer;
136 ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
138 if ([_tracks count] == 0) {
139 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
143 //Build the MD5 response string we send along with the request
144 buffer = malloc(EVP_MD_size(EVP_md5()));
145 EVP_DigestInit(&ctx, EVP_md5());
146 EVP_DigestUpdate(&ctx, pass, strlen(pass));
147 EVP_DigestFinal(&ctx, buffer, NULL);
149 for (i = 0; i < 16; i++) {
150 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
154 buffer = malloc(EVP_MD_size(EVP_md5()));
155 char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
156 EVP_DigestInit(&ctx, EVP_md5());
157 EVP_DigestUpdate(&ctx, cat, strlen(cat));
158 EVP_DigestFinal(&ctx, buffer, NULL);
161 for (i = 0; i < 16; i++) {
162 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
166 authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
167 requestString = [[NSMutableString alloc] initWithString:authString];
168 [authString release];
170 //We can only submit ten tracks at a time
171 for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
172 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
173 NSString *trackString;
175 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);
176 [requestString appendString:trackString];
177 [trackString release];
180 //Create and send the request
181 NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30] mutableCopy];
182 [request setHTTPMethod:@"POST"];
183 [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
184 _currentStatus = AudioscrobblerSubmittingTracksStatus;
185 _responseData = [[NSMutableData alloc] init];
186 [NSURLConnection connectionWithRequest:request delegate:self];
187 [requestString release];
190 //If we have tracks left, submit again after the interval seconds
193 - (void)handleAudioscrobblerNotification:(NSNotification *)note
195 if ([[note name] isEqualToString:@"AudioscrobblerHandshakeComplete"]) {
196 if ([_tracks count] > 0) {
197 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
204 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
206 ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
209 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
211 [_responseData appendData:data];
214 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
216 NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
217 NSArray *lines = [string componentsSeparatedByString:@"\n"];
218 NSString *responseAction = nil;
220 if ([lines count] > 0) {
221 responseAction = [lines objectAtIndex:0];
224 if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
225 if ([lines count] < 2) {
226 //We have a protocol error
228 if ([responseAction isEqualToString:@"UPTODATE"]) {
229 if ([lines count] >= 4) {
230 _md5Challenge = [[lines objectAtIndex:1] retain];
231 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
232 _handshakeCompleted = YES;
233 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
235 //We have a protocol error
238 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"]) {
239 //Something plus update action
240 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
242 } else if ([responseAction isEqualToString:@"BADUSER"]) {
247 } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
248 if ([responseAction isEqualToString:@"OK"]) {
249 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
251 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
256 //Handle the final INTERVAL response
257 if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
258 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
259 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
260 [_delayDate release];
261 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
263 ITDebugLog(@"No interval response.");
264 //We have a protocol error
268 [_responseData release];