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