Implemented reauthentication when a session ticket is invalidated by another computer.
[MenuTunes.git] / AudioscrobblerController.m
index 4addcaf..12c2f26 100644 (file)
 #import <openssl/evp.h>
 #import <ITFoundation/ITDebug.h>
 
+#define AUDIOSCROBBLER_ID @"mtu"
+#define AUDIOSCROBBLER_VERSION [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]
+
 static AudioscrobblerController *_sharedController = nil;
 
 @implementation AudioscrobblerController
 
-/*+ (void)load
-{
-       NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-       [[AudioscrobblerController sharedController] submitTrack:@"Immigrant Song" artist:@"Led Zeppelin" album:@"How The West Was Won" length:221];
-       [[AudioscrobblerController sharedController] submitTrack:@"Comfortably Numb" artist:@"Pink Floyd" album:@"The Wall" length:384];
-       [[AudioscrobblerController sharedController] submitTracks];
-       [pool release];
-}*/
-
 + (AudioscrobblerController *)sharedController
 {
        if (!_sharedController) {
@@ -48,25 +42,63 @@ static AudioscrobblerController *_sharedController = nil;
                _md5Challenge = @"rawr";
                _postURL = [NSURL URLWithString:@"http://audioscrobbler.com/"];*/
                
-               _delayDate = nil;
-               _responseData = nil;
+               _delayDate = [[NSDate date] retain];
+               _responseData = [[NSMutableData alloc] init];
                _tracks = [[NSMutableArray alloc] init];
-               [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioscrobblerNotification:) name:nil object:self];
+               _submitTracks = [[NSMutableArray alloc] init];
+               [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioscrobblerNotification:) name:@"AudioscrobblerHandshakeComplete" object:self];
        }
        return self;
 }
 
 - (void)dealloc
 {
+       [_lastStatus release];
        [_md5Challenge release];
        [_postURL release];
        [_responseData release];
+       [_submitTracks release];
        [_tracks release];
+       [_delayDate release];
        [super dealloc];
 }
 
+- (NSString *)lastStatus
+{
+       return _lastStatus;
+}
+
 - (void)attemptHandshake
 {
+       [self attemptHandshake:NO];
+}
+
+- (void)attemptHandshake:(BOOL)force
+{
+       if (_handshakeCompleted && !force) {
+               return;
+       }
+       
+       //If we've already tried to handshake three times in a row unsuccessfully, set the attempt count to -3
+       if (_handshakeAttempts > 3) {
+               ITDebugLog(@"Audioscrobbler: Maximum handshake limit reached (3). Retrying when handshake attempts reach zero.");
+               _handshakeAttempts = -3;
+               
+               //Remove any tracks we were trying to submit, just to be safe
+               [_submitTracks removeAllObjects];
+               
+               return;
+       }
+       
+       //Increment the number of times we've tried to handshake
+       _handshakeAttempts++;
+       
+       //We're still on our self-imposed cooldown time.
+       if (_handshakeAttempts < 0) {
+               ITDebugLog(@"Audioscrobbler: Handshake timeout. Retrying when handshake attempts reach zero.");
+               return;
+       }
+       
        //Delay if we haven't met the interval time limit
        NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
        if (interval > 0) {
@@ -75,13 +107,17 @@ static AudioscrobblerController *_sharedController = nil;
                return;
        }
        
-       if (!_handshakeCompleted) {
-               NSString *version = [[[NSBundle bundleWithPath:[[NSWorkspace sharedWorkspace] fullPathForApplication:@"iTunes.app"]] infoDictionary] objectForKey:@"CFBundleVersion"], *user = @"Tristrex";
-               NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=tst&v=%@&u=%@", version, user]];
+       NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
+       if (!_handshakeCompleted && user) {
+               NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
+               
+               [_lastStatus release];
+               _lastStatus = [NSLocalizedString(@"audioscrobbler_handshaking", @"Attempting to handshake with server") retain];
+               [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
                
                _currentStatus = AudioscrobblerRequestingHandshakeStatus;
-               _responseData = [[NSMutableData alloc] init];
-               [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30] delegate:self];
+               //_responseData = [[NSMutableData alloc] init];
+               [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
        }
 }
 
@@ -111,7 +147,22 @@ static AudioscrobblerController *_sharedController = nil;
 - (void)submitTracks
 {
        if (!_handshakeCompleted) {
-               [self attemptHandshake];
+               [self attemptHandshake:NO];
+               return;
+       }
+       
+       ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
+       
+       if ([_tracks count] == 0) {
+               ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
+               return;
+       }
+       
+       NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
+       char *pass = (char *)[passString UTF8String];
+       
+       if (passString == nil) {
+               ITDebugLog(@"Audioscrobbler: Access denied to user password");
                return;
        }
        
@@ -125,18 +176,9 @@ static AudioscrobblerController *_sharedController = nil;
        int i;
        NSMutableString *requestString;
        NSString *authString, *responseHash = @"";
-       NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
-       char *pass = (char *)[[PreferencesController getKeychainItemPasswordForUser:user] UTF8String];
        unsigned char *buffer;
        EVP_MD_CTX ctx;
        
-       ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
-       
-       if ([_tracks count] == 0) {
-               ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
-               return;
-       }
-       
        //Build the MD5 response string we send along with the request
        buffer = malloc(EVP_MD_size(EVP_md5()));
        EVP_DigestInit(&ctx, EVP_md5());
@@ -167,32 +209,58 @@ static AudioscrobblerController *_sharedController = nil;
        //We can only submit ten tracks at a time
        for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
                NSDictionary *nextTrack = [_tracks objectAtIndex:i];
-               NSString *trackString;
+               NSString *artistEscaped, *titleEscaped, *albumEscaped, *timeEscaped, *ampersand = @"&";
                
-               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);
-               [requestString appendString:trackString];
-               [trackString release];
+               //Escape each of the individual parameters we're sending
+               artistEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"artist"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
+               titleEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"title"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
+               albumEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"album"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
+               timeEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"time"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
+               
+               [requestString appendString:[NSString stringWithFormat:@"&a[%i]=%@&t[%i]=%@&b[%i]=%@&m[%i]=&l[%i]=%@&i[%i]=%@", i, artistEscaped,
+                                                                                                                                                                                                                                               i, titleEscaped,
+                                                                                                                                                                                                                                               i, albumEscaped,
+                                                                                                                                                                                                                                               i,
+                                                                                                                                                                                                                                               i, [nextTrack objectForKey:@"length"],
+                                                                                                                                                                                                                                               i, timeEscaped]];
+               
+               //Release the escaped strings
+               [artistEscaped release];
+               [titleEscaped release];
+               [albumEscaped release];
+               [timeEscaped release];
+               
+               [_submitTracks addObject:nextTrack];
        }
        
+       ITDebugLog(@"Audioscrobbler: Sending track submission request");
+       [_lastStatus release];
+       _lastStatus = [NSLocalizedString(@"audioscrobbler_submitting", @"Submitting tracks to server") retain];
+       [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
+       
        //Create and send the request
-       NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30] mutableCopy];
+       NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
        _currentStatus = AudioscrobblerSubmittingTracksStatus;
-       _responseData = [[NSMutableData alloc] init];
+       //_responseData = [[NSMutableData alloc] init];
+       [_responseData setData:nil];
        [NSURLConnection connectionWithRequest:request delegate:self];
        [requestString release];
        [request release];
        
+       //For now we're not going to cache results, as it is less of a headache
+       //[_tracks removeObjectsInArray:_submitTracks];
+       [_tracks removeAllObjects];
+       //[_submitTracks removeAllObjects];
+       
        //If we have tracks left, submit again after the interval seconds
 }
 
 - (void)handleAudioscrobblerNotification:(NSNotification *)note
 {
-       if ([[note name] isEqualToString:@"AudioscrobblerHandshakeComplete"]) {
-               if ([_tracks count] > 0) {
-                       [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
-               }
+       if ([_tracks count] > 0) {
+               [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
        }
 }
 
@@ -200,6 +268,10 @@ static AudioscrobblerController *_sharedController = nil;
 
 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 {
+       [_responseData setData:nil];
+       [_lastStatus release];
+       _lastStatus = [[NSString stringWithFormat:NSLocalizedString(@"audioscrobbler_error", @"Error - %@"), [error localizedDescription]] retain];
+       [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:self userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
        ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
 }
 
@@ -212,41 +284,82 @@ static AudioscrobblerController *_sharedController = nil;
 {
        NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
        NSArray *lines = [string componentsSeparatedByString:@"\n"];
-       NSString *responseAction = nil;
+       NSString *responseAction = nil, *key = nil, *comment = nil;
        
        if ([lines count] > 0) {
                responseAction = [lines objectAtIndex:0];
        }
-       
+       ITDebugLog(@"Audioscrobbler: Response %@", string);
        if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
                if ([lines count] < 2) {
                        //We have a protocol error
                }
-               if ([responseAction isEqualToString:@"UPTODATE"]) {
+               if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
                        if ([lines count] >= 4) {
                                _md5Challenge = [[lines objectAtIndex:1] retain];
                                _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
                                _handshakeCompleted = YES;
                                [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
+                               key = @"audioscrobbler_handshake_complete";
+                               comment = @"Handshake complete";
+                               _handshakeAttempts = 0;
                        } else {
                                //We have a protocol error
                        }
-                       //Something
-               } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"]) {
-                       //Something plus update action
                } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
+                       ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
+                       key = @"audioscrobbler_handshake_failed";
+                       comment = @"Handshake failed";
                        //We have a error
                } else if ([responseAction isEqualToString:@"BADUSER"]) {
+                       ITDebugLog(@"Audioscrobbler: Bad user name");
+                       key = @"audioscrobbler_bad_user";
+                       comment = @"Handshake failed - invalid user name";
                        //We have a bad user
+                       
+                       //Don't count this as a bad handshake attempt
+                       _handshakeAttempts = 0;
                } else {
-                       //We have a protocol
+                       ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
+                       key = @"audioscrobbler_protocol_error";
+                       comment = @"Internal protocol error";
+                       //We have a protocol error
                }
        } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
                if ([responseAction isEqualToString:@"OK"]) {
+                       ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
+                       /*[_tracks removeObjectsInArray:_submitTracks];
+                       [_submitTracks removeAllObjects];*/
+                       [_submitTracks removeAllObjects];
+                       if ([_tracks count] > 0) {
+                               ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
+                               [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
+                       }
+                       key = @"audioscrobbler_submission_ok";
+                       comment = @"Last track submission successful";
                } else if ([responseAction isEqualToString:@"BADAUTH"]) {
+                       ITDebugLog(@"Audioscrobbler: Bad password");
+                       key = @"audioscrobbler_bad_password";
+                       comment = @"Last track submission failed - invalid password";
                        //Bad auth
+                       
+                       //Add the tracks we were trying to submit back into the submission queue
+                       [_tracks addObjectsFromArray:_submitTracks];
+                       
+                       _handshakeCompleted = NO;
+                       
+                       //If we were previously valid with the same login name, try reauthenticating and sending again
+                       [self attemptHandshake:YES];
                } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
+                       ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
+                       key = @"audioscrobbler_submission_failed";
+                       comment = @"Last track submission failed - see console for error";
                        //Failed
+                       
+                       //We got an unknown error. To be safe we're going to remove the tracks we tried to submit
+                       [_submitTracks removeAllObjects];
+                       
+                       _handshakeCompleted = NO;
                }
        }
        
@@ -260,9 +373,17 @@ static AudioscrobblerController *_sharedController = nil;
                ITDebugLog(@"No interval response.");
                //We have a protocol error
        }
-       
+       [_lastStatus release];
+       _lastStatus = [NSLocalizedString(key, comment) retain];
+       [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerStatusChanged" object:nil userInfo:[NSDictionary dictionaryWithObject:_lastStatus forKey:@"StatusString"]];
        [string release];
-       [_responseData release];
+       [_responseData setData:nil];
+}
+
+-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
+{
+       //Don't cache any Audioscrobbler communication
+       return nil;
 }
 
 @end