Removed Audioscrobbler NSLog debug
[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                 [_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         [NSURLConnection connectionWithRequest:request delegate:self];
228         [requestString release];
229         [request release];
230         
231         //For now we're not going to cache results, as it is less of a headache
232         //[_tracks removeObjectsInArray:_submitTracks];
233         [_tracks removeAllObjects];
234         [_submitTracks removeAllObjects];
235         
236         //If we have tracks left, submit again after the interval seconds
237 }
238
239 - (void)handleAudioscrobblerNotification:(NSNotification *)note
240 {
241         if ([_tracks count] > 0) {
242                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
243         }
244 }
245
246 #pragma mark -
247
248 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
249 {
250         [_responseData release];
251         [_lastStatus release];
252         _lastStatus = [[NSString stringWithFormat:NSLocalizedString(@"audioscrobbler_error", @"Error - %@"), [error localizedDescription]] retain];
253         [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:self userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
254         ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
255 }
256
257 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
258 {
259         [_responseData appendData:data];
260 }
261
262 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
263 {
264         NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
265         NSArray *lines = [string componentsSeparatedByString:@"\n"];
266         NSString *responseAction = nil, *key = nil, *comment = nil;
267         
268         if ([lines count] > 0) {
269                 responseAction = [lines objectAtIndex:0];
270         }
271         ITDebugLog(@"Audioscrobbler: Response %@", string);
272         if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
273                 if ([lines count] < 2) {
274                         //We have a protocol error
275                 }
276                 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
277                         if ([lines count] >= 4) {
278                                 _md5Challenge = [[lines objectAtIndex:1] retain];
279                                 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
280                                 _handshakeCompleted = YES;
281                                 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
282                                 key = @"audioscrobbler_handshake_complete";
283                                 comment = @"Handshake complete";
284                         } else {
285                                 //We have a protocol error
286                         }
287                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
288                         ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
289                         key = @"audioscrobbler_handshake_failed";
290                         comment = @"Handshake failed";
291                         //We have a error
292                 } else if ([responseAction isEqualToString:@"BADUSER"]) {
293                         ITDebugLog(@"Audioscrobbler: Bad user name");
294                         key = @"audioscrobbler_bad_user";
295                         comment = @"Handshake failed - invalid user name";
296                         //We have a bad user
297                 } else {
298                         ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
299                         key = @"audioscrobbler_protocol_error";
300                         comment = @"Internal protocol error";
301                         //We have a protocol error
302                 }
303         } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
304                 if ([responseAction isEqualToString:@"OK"]) {
305                         ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
306                         /*[_tracks removeObjectsInArray:_submitTracks];
307                         [_submitTracks removeAllObjects];*/
308                         if ([_tracks count] > 0) {
309                                 ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
310                                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
311                         }
312                         key = @"audioscrobbler_submission_ok";
313                         comment = @"Last track submission successful";
314                 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
315                         ITDebugLog(@"Audioscrobbler: Bad password");
316                         key = @"audioscrobbler_bad_password";
317                         comment = @"Last track submission failed - invalid password";
318                         //Bad auth
319                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
320                         ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
321                         key = @"audioscrobbler_submission_failed";
322                         comment = @"Last track submission failed - see console for error";
323                         //Failed
324                 }
325         }
326         
327         //Handle the final INTERVAL response
328         if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
329                 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
330                 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
331                 [_delayDate release];
332                 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
333         } else {
334                 ITDebugLog(@"No interval response.");
335                 //We have a protocol error
336         }
337         [_lastStatus release];
338         _lastStatus = [NSLocalizedString(key, comment) retain];
339         [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
340         [string release];
341         [_responseData release];
342 }
343
344 -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
345 {
346         //Don't cache any Audioscrobbler communication
347         return nil;
348 }
349
350 @end