Using the universal libValidate. Fixed a small Audioscrobbler crash that could happen...
[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         //Delay if we haven't met the interval time limit
83         NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
84         if (interval > 0) {
85                 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
86                 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
87                 return;
88         }
89         
90         NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
91         if (!_handshakeCompleted && user) {
92                 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
93                 
94                 [_lastStatus release];
95                 _lastStatus = [NSLocalizedString(@"audioscrobbler_handshaking", @"Attempting to handshake with server") retain];
96                 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
97                 
98                 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
99                 //_responseData = [[NSMutableData alloc] init];
100                 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
101         }
102 }
103
104 - (BOOL)handshakeCompleted
105 {
106         return _handshakeCompleted;
107 }
108
109 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
110 {
111         ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
112         NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
113                                                                                                                                                 @"title",
114                                                                                                                                                 artist,
115                                                                                                                                                 @"artist",
116                                                                                                                                                 (album == nil) ? @"" : album,
117                                                                                                                                                 @"album",
118                                                                                                                                                 [NSString stringWithFormat:@"%i", length],
119                                                                                                                                                 @"length",
120                                                                                                                                                 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
121                                                                                                                                                 @"time",
122                                                                                                                                                 nil, nil];
123         [_tracks addObject:newTrack];
124         [self submitTracks];
125 }
126
127 - (void)submitTracks
128 {
129         if (!_handshakeCompleted) {
130                 [self attemptHandshake:NO];
131                 return;
132         }
133         
134         NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
135         char *pass = (char *)[passString UTF8String];
136         
137         if (passString == nil) {
138                 ITDebugLog(@"Audioscrobbler: Access denied to user password");
139                 return;
140         }
141         
142         NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
143         if (interval > 0) {
144                 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
145                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
146                 return;
147         }
148         
149         int i;
150         NSMutableString *requestString;
151         NSString *authString, *responseHash = @"";
152         unsigned char *buffer;
153         EVP_MD_CTX ctx;
154         
155         ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
156         
157         if ([_tracks count] == 0) {
158                 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
159                 return;
160         }
161         
162         //Build the MD5 response string we send along with the request
163         buffer = malloc(EVP_MD_size(EVP_md5()));
164         EVP_DigestInit(&ctx, EVP_md5());
165         EVP_DigestUpdate(&ctx, pass, strlen(pass));
166         EVP_DigestFinal(&ctx, buffer, NULL);
167         
168         for (i = 0; i < 16; i++) {
169                 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
170         }
171         
172         free(buffer);
173         buffer = malloc(EVP_MD_size(EVP_md5()));
174         char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
175         EVP_DigestInit(&ctx, EVP_md5());
176         EVP_DigestUpdate(&ctx, cat, strlen(cat));
177         EVP_DigestFinal(&ctx, buffer, NULL);
178         
179         responseHash = @"";
180         for (i = 0; i < 16; i++) {
181                 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
182         }
183         free(buffer);
184         
185         authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
186         requestString = [[NSMutableString alloc] initWithString:authString];
187         [authString release];
188         
189         //We can only submit ten tracks at a time
190         for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
191                 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
192                 NSString *artistEscaped, *titleEscaped, *albumEscaped, *timeEscaped, *ampersand = @"&";
193                 
194                 //Escape each of the individual parameters we're sending
195                 artistEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"artist"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
196                 titleEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"title"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
197                 albumEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"album"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
198                 timeEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"time"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
199                 
200                 [requestString appendString:[NSString stringWithFormat:@"&a[%i]=%@&t[%i]=%@&b[%i]=%@&m[%i]=&l[%i]=%@&i[%i]=%@", i, artistEscaped,
201                                                                                                                                                                                                                                                 i, titleEscaped,
202                                                                                                                                                                                                                                                 i, albumEscaped,
203                                                                                                                                                                                                                                                 i,
204                                                                                                                                                                                                                                                 i, [nextTrack objectForKey:@"length"],
205                                                                                                                                                                                                                                                 i, timeEscaped]];
206                 
207                 //Release the escaped strings
208                 [artistEscaped release];
209                 [titleEscaped release];
210                 [albumEscaped release];
211                 [timeEscaped release];
212                 
213                 [_submitTracks addObject:nextTrack];
214         }
215         
216         ITDebugLog(@"Audioscrobbler: Sending track submission request");
217         [_lastStatus release];
218         _lastStatus = [NSLocalizedString(@"audioscrobbler_submitting", @"Submitting tracks to server") retain];
219         [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
220         
221         //Create and send the request
222         NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
223         [request setHTTPMethod:@"POST"];
224         [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
225         _currentStatus = AudioscrobblerSubmittingTracksStatus;
226         //_responseData = [[NSMutableData alloc] init];
227         [_responseData setData:nil];
228         [NSURLConnection connectionWithRequest:request delegate:self];
229         [requestString release];
230         [request release];
231         
232         //For now we're not going to cache results, as it is less of a headache
233         //[_tracks removeObjectsInArray:_submitTracks];
234         [_tracks removeAllObjects];
235         [_submitTracks removeAllObjects];
236         
237         //If we have tracks left, submit again after the interval seconds
238 }
239
240 - (void)handleAudioscrobblerNotification:(NSNotification *)note
241 {
242         if ([_tracks count] > 0) {
243                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
244         }
245 }
246
247 #pragma mark -
248
249 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
250 {
251         [_responseData setData:nil];
252         [_lastStatus release];
253         _lastStatus = [[NSString stringWithFormat:NSLocalizedString(@"audioscrobbler_error", @"Error - %@"), [error localizedDescription]] retain];
254         [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:self userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
255         ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
256 }
257
258 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
259 {
260         [_responseData appendData:data];
261 }
262
263 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
264 {
265         NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
266         NSArray *lines = [string componentsSeparatedByString:@"\n"];
267         NSString *responseAction = nil, *key = nil, *comment = nil;
268         
269         if ([lines count] > 0) {
270                 responseAction = [lines objectAtIndex:0];
271         }
272         ITDebugLog(@"Audioscrobbler: Response %@", string);
273         if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
274                 if ([lines count] < 2) {
275                         //We have a protocol error
276                 }
277                 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
278                         if ([lines count] >= 4) {
279                                 _md5Challenge = [[lines objectAtIndex:1] retain];
280                                 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
281                                 _handshakeCompleted = YES;
282                                 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
283                                 key = @"audioscrobbler_handshake_complete";
284                                 comment = @"Handshake complete";
285                         } else {
286                                 //We have a protocol error
287                         }
288                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
289                         ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
290                         key = @"audioscrobbler_handshake_failed";
291                         comment = @"Handshake failed";
292                         //We have a error
293                 } else if ([responseAction isEqualToString:@"BADUSER"]) {
294                         ITDebugLog(@"Audioscrobbler: Bad user name");
295                         key = @"audioscrobbler_bad_user";
296                         comment = @"Handshake failed - invalid user name";
297                         //We have a bad user
298                 } else {
299                         ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
300                         key = @"audioscrobbler_protocol_error";
301                         comment = @"Internal protocol error";
302                         //We have a protocol error
303                 }
304         } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
305                 if ([responseAction isEqualToString:@"OK"]) {
306                         ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
307                         /*[_tracks removeObjectsInArray:_submitTracks];
308                         [_submitTracks removeAllObjects];*/
309                         if ([_tracks count] > 0) {
310                                 ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
311                                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
312                         }
313                         key = @"audioscrobbler_submission_ok";
314                         comment = @"Last track submission successful";
315                 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
316                         ITDebugLog(@"Audioscrobbler: Bad password");
317                         key = @"audioscrobbler_bad_password";
318                         comment = @"Last track submission failed - invalid password";
319                         //Bad auth
320                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
321                         ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
322                         key = @"audioscrobbler_submission_failed";
323                         comment = @"Last track submission failed - see console for error";
324                         //Failed
325                 }
326         }
327         
328         //Handle the final INTERVAL response
329         if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
330                 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
331                 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
332                 [_delayDate release];
333                 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
334         } else {
335                 ITDebugLog(@"No interval response.");
336                 //We have a protocol error
337         }
338         [_lastStatus release];
339         _lastStatus = [NSLocalizedString(key, comment) retain];
340         [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
341         [string release];
342         [_responseData setData:nil];
343 }
344
345 -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
346 {
347         //Don't cache any Audioscrobbler communication
348         return nil;
349 }
350
351 @end