Bumped to version 1.7.1
[MenuTunes.git] / AudioscrobblerController.m
1 /*
2  *      MenuTunes
3  *  AudioscrobblerController
4  *    Audioscrobbler Support Class
5  *
6  *  Original Author : Kent Sutherland <kent.sutherland@ithinksw.com>
7  *   Responsibility : Kent Sutherland <kent.sutherland@ithinksw.com>
8  *
9  *  Copyright (c) 2005 iThink Software.
10  *  All Rights Reserved
11  *
12  */
13
14 #import "AudioscrobblerController.h"
15 #import "PreferencesController.h"
16 #import <openssl/evp.h>
17 #import <ITFoundation/ITDebug.h>
18
19 #define AUDIOSCROBBLER_ID @"mtu"
20 #define AUDIOSCROBBLER_VERSION [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]
21
22 static AudioscrobblerController *_sharedController = nil;
23
24 @implementation AudioscrobblerController
25
26 + (AudioscrobblerController *)sharedController
27 {
28         if (!_sharedController) {
29                 _sharedController = [[AudioscrobblerController alloc] init];
30         }
31         return _sharedController;
32 }
33
34 - (id)init
35 {
36         if ( (self = [super init]) ) {
37                 _handshakeCompleted = NO;
38                 _md5Challenge = nil;
39                 _postURL = nil;
40                 
41                 /*_handshakeCompleted = YES;
42                 _md5Challenge = @"rawr";
43                 _postURL = [NSURL URLWithString:@"http://audioscrobbler.com/"];*/
44                 
45                 _delayDate = [[NSDate date] retain];
46                 _responseData = [[NSMutableData alloc] init];
47                 _tracks = [[NSMutableArray alloc] init];
48                 _submitTracks = [[NSMutableArray alloc] init];
49                 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioscrobblerNotification:) name:@"AudioscrobblerHandshakeComplete" object:self];
50         }
51         return self;
52 }
53
54 - (void)dealloc
55 {
56         [_lastStatus release];
57         [_md5Challenge release];
58         [_postURL release];
59         [_responseData release];
60         [_submitTracks release];
61         [_tracks release];
62         [_delayDate release];
63         [super dealloc];
64 }
65
66 - (NSString *)lastStatus
67 {
68         return _lastStatus;
69 }
70
71 - (void)attemptHandshake
72 {
73         [self attemptHandshake:NO];
74 }
75
76 - (void)attemptHandshake:(BOOL)force
77 {
78         if (_handshakeCompleted && !force) {
79                 return;
80         }
81         
82         //If we've already tried to handshake three times in a row unsuccessfully, set the attempt count to -3
83         if (_handshakeAttempts > 3) {
84                 ITDebugLog(@"Audioscrobbler: Maximum handshake limit reached (3). Retrying when handshake attempts reach zero.");
85                 _handshakeAttempts = -3;
86                 
87                 //Remove any tracks we were trying to submit, just to be safe
88                 [_submitTracks removeAllObjects];
89                 
90                 return;
91         }
92         
93         //Increment the number of times we've tried to handshake
94         _handshakeAttempts++;
95         
96         //We're still on our self-imposed cooldown time.
97         if (_handshakeAttempts < 0) {
98                 ITDebugLog(@"Audioscrobbler: Handshake timeout. Retrying when handshake attempts reach zero.");
99                 return;
100         }
101         
102         //Delay if we haven't met the interval time limit
103         NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
104         if (interval > 0) {
105                 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
106                 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
107                 return;
108         }
109         
110         NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
111         if (!_handshakeCompleted && user) {
112                 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
113                 
114                 [_lastStatus release];
115                 _lastStatus = [NSLocalizedString(@"audioscrobbler_handshaking", @"Attempting to handshake with server") retain];
116                 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
117                 
118                 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
119                 //_responseData = [[NSMutableData alloc] init];
120                 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
121         }
122 }
123
124 - (BOOL)handshakeCompleted
125 {
126         return _handshakeCompleted;
127 }
128
129 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
130 {
131         ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
132         NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
133                                                                                                                                                 @"title",
134                                                                                                                                                 artist,
135                                                                                                                                                 @"artist",
136                                                                                                                                                 (album == nil) ? @"" : album,
137                                                                                                                                                 @"album",
138                                                                                                                                                 [NSString stringWithFormat:@"%i", length],
139                                                                                                                                                 @"length",
140                                                                                                                                                 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
141                                                                                                                                                 @"time",
142                                                                                                                                                 nil, nil];
143         [_tracks addObject:newTrack];
144         [self submitTracks];
145 }
146
147 - (void)submitTracks
148 {
149         if (!_handshakeCompleted) {
150                 [self attemptHandshake:NO];
151                 return;
152         }
153         
154         ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
155         
156         if ([_tracks count] == 0) {
157                 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
158                 return;
159         }
160         
161         NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
162         char *pass = (char *)[passString UTF8String];
163         
164         if (passString == nil) {
165                 ITDebugLog(@"Audioscrobbler: Access denied to user password");
166                 return;
167         }
168         
169         NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
170         if (interval > 0) {
171                 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
172                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
173                 return;
174         }
175         
176         int i;
177         NSMutableString *requestString;
178         NSString *authString, *responseHash = @"";
179         unsigned char *buffer;
180         EVP_MD_CTX ctx;
181         
182         //Build the MD5 response string we send along with the request
183         buffer = malloc(EVP_MD_size(EVP_md5()));
184         EVP_DigestInit(&ctx, EVP_md5());
185         EVP_DigestUpdate(&ctx, pass, strlen(pass));
186         EVP_DigestFinal(&ctx, buffer, NULL);
187         
188         for (i = 0; i < 16; i++) {
189                 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
190         }
191         
192         free(buffer);
193         buffer = malloc(EVP_MD_size(EVP_md5()));
194         char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
195         EVP_DigestInit(&ctx, EVP_md5());
196         EVP_DigestUpdate(&ctx, cat, strlen(cat));
197         EVP_DigestFinal(&ctx, buffer, NULL);
198         
199         responseHash = @"";
200         for (i = 0; i < 16; i++) {
201                 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
202         }
203         free(buffer);
204         
205         authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
206         requestString = [[NSMutableString alloc] initWithString:authString];
207         [authString release];
208         
209         //We can only submit ten tracks at a time
210         for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
211                 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
212                 NSString *artistEscaped, *titleEscaped, *albumEscaped, *timeEscaped, *ampersand = @"&";
213                 
214                 //Escape each of the individual parameters we're sending
215                 artistEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"artist"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
216                 titleEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"title"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
217                 albumEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"album"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
218                 timeEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"time"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
219                 
220                 [requestString appendString:[NSString stringWithFormat:@"&a[%i]=%@&t[%i]=%@&b[%i]=%@&m[%i]=&l[%i]=%@&i[%i]=%@", i, artistEscaped,
221                                                                                                                                                                                                                                                 i, titleEscaped,
222                                                                                                                                                                                                                                                 i, albumEscaped,
223                                                                                                                                                                                                                                                 i,
224                                                                                                                                                                                                                                                 i, [nextTrack objectForKey:@"length"],
225                                                                                                                                                                                                                                                 i, timeEscaped]];
226                 
227                 //Release the escaped strings
228                 [artistEscaped release];
229                 [titleEscaped release];
230                 [albumEscaped release];
231                 [timeEscaped release];
232                 
233                 [_submitTracks addObject:nextTrack];
234         }
235         
236         ITDebugLog(@"Audioscrobbler: Sending track submission request");
237         [_lastStatus release];
238         _lastStatus = [NSLocalizedString(@"audioscrobbler_submitting", @"Submitting tracks to server") retain];
239         [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
240         
241         //Create and send the request
242         NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
243         [request setHTTPMethod:@"POST"];
244         [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
245         _currentStatus = AudioscrobblerSubmittingTracksStatus;
246         //_responseData = [[NSMutableData alloc] init];
247         [_responseData setData:nil];
248         [NSURLConnection connectionWithRequest:request delegate:self];
249         [requestString release];
250         [request release];
251         
252         //For now we're not going to cache results, as it is less of a headache
253         //[_tracks removeObjectsInArray:_submitTracks];
254         [_tracks removeAllObjects];
255         //[_submitTracks removeAllObjects];
256         
257         //If we have tracks left, submit again after the interval seconds
258 }
259
260 - (void)handleAudioscrobblerNotification:(NSNotification *)note
261 {
262         if ([_tracks count] > 0) {
263                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
264         }
265 }
266
267 #pragma mark -
268
269 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
270 {
271         [_responseData setData:nil];
272         [_lastStatus release];
273         _lastStatus = [[NSString stringWithFormat:NSLocalizedString(@"audioscrobbler_error", @"Error - %@"), [error localizedDescription]] retain];
274         [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:self userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
275         ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
276 }
277
278 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
279 {
280         [_responseData appendData:data];
281 }
282
283 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
284 {
285         NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
286         NSArray *lines = [string componentsSeparatedByString:@"\n"];
287         NSString *responseAction = nil, *key = nil, *comment = nil;
288         
289         if ([lines count] > 0) {
290                 responseAction = [lines objectAtIndex:0];
291         }
292         ITDebugLog(@"Audioscrobbler: Response %@", string);
293         if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
294                 if ([lines count] < 2) {
295                         //We have a protocol error
296                 }
297                 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
298                         if ([lines count] >= 4) {
299                                 _md5Challenge = [[lines objectAtIndex:1] retain];
300                                 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
301                                 _handshakeCompleted = YES;
302                                 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
303                                 key = @"audioscrobbler_handshake_complete";
304                                 comment = @"Handshake complete";
305                                 _handshakeAttempts = 0;
306                         } else {
307                                 //We have a protocol error
308                         }
309                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
310                         ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
311                         key = @"audioscrobbler_handshake_failed";
312                         comment = @"Handshake failed";
313                         //We have a error
314                 } else if ([responseAction isEqualToString:@"BADUSER"]) {
315                         ITDebugLog(@"Audioscrobbler: Bad user name");
316                         key = @"audioscrobbler_bad_user";
317                         comment = @"Handshake failed - invalid user name";
318                         //We have a bad user
319                         
320                         //Don't count this as a bad handshake attempt
321                         _handshakeAttempts = 0;
322                 } else {
323                         ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
324                         key = @"audioscrobbler_protocol_error";
325                         comment = @"Internal protocol error";
326                         //We have a protocol error
327                 }
328         } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
329                 if ([responseAction isEqualToString:@"OK"]) {
330                         ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
331                         /*[_tracks removeObjectsInArray:_submitTracks];
332                         [_submitTracks removeAllObjects];*/
333                         [_submitTracks removeAllObjects];
334                         if ([_tracks count] > 0) {
335                                 ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
336                                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
337                         }
338                         key = @"audioscrobbler_submission_ok";
339                         comment = @"Last track submission successful";
340                 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
341                         ITDebugLog(@"Audioscrobbler: Bad password");
342                         key = @"audioscrobbler_bad_password";
343                         comment = @"Last track submission failed - invalid password";
344                         //Bad auth
345                         
346                         //Add the tracks we were trying to submit back into the submission queue
347                         [_tracks addObjectsFromArray:_submitTracks];
348                         
349                         _handshakeCompleted = NO;
350                         
351                         //If we were previously valid with the same login name, try reauthenticating and sending again
352                         [self attemptHandshake:YES];
353                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
354                         ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
355                         key = @"audioscrobbler_submission_failed";
356                         comment = @"Last track submission failed - see console for error";
357                         //Failed
358                         
359                         //We got an unknown error. To be safe we're going to remove the tracks we tried to submit
360                         [_submitTracks removeAllObjects];
361                         
362                         _handshakeCompleted = NO;
363                 }
364         }
365         
366         //Handle the final INTERVAL response
367         if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
368                 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
369                 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
370                 [_delayDate release];
371                 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
372         } else {
373                 ITDebugLog(@"No interval response.");
374                 //We have a protocol error
375         }
376         [_lastStatus release];
377         _lastStatus = [NSLocalizedString(key, comment) retain];
378         [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
379         [string release];
380         [_responseData setData:nil];
381 }
382
383 -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
384 {
385         //Don't cache any Audioscrobbler communication
386         return nil;
387 }
388
389 @end