Added a new currentSongDuration method to the remote.
[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 static AudioscrobblerController *_sharedController = nil;
20
21 @implementation AudioscrobblerController
22
23 /*+ (void)load
24 {
25         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
26         [[AudioscrobblerController sharedController] submitTrack:@"Immigrant Song" artist:@"Led Zeppelin" album:@"How The West Was Won" length:221];
27         [[AudioscrobblerController sharedController] submitTrack:@"Comfortably Numb" artist:@"Pink Floyd" album:@"The Wall" length:384];
28         [[AudioscrobblerController sharedController] submitTracks];
29         [pool release];
30 }*/
31
32 + (AudioscrobblerController *)sharedController
33 {
34         if (!_sharedController) {
35                 _sharedController = [[AudioscrobblerController alloc] init];
36         }
37         return _sharedController;
38 }
39
40 - (id)init
41 {
42         if ( (self = [super init]) ) {
43                 _handshakeCompleted = NO;
44                 _md5Challenge = nil;
45                 _postURL = nil;
46                 
47                 /*_handshakeCompleted = YES;
48                 _md5Challenge = @"rawr";
49                 _postURL = [NSURL URLWithString:@"http://audioscrobbler.com/"];*/
50                 
51                 _delayDate = nil;
52                 _responseData = nil;
53                 _tracks = [[NSMutableArray alloc] init];
54                 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioscrobblerNotification:) name:nil object:self];
55         }
56         return self;
57 }
58
59 - (void)dealloc
60 {
61         [_md5Challenge release];
62         [_postURL release];
63         [_responseData release];
64         [_tracks release];
65         [super dealloc];
66 }
67
68 - (void)attemptHandshake
69 {
70         //Delay if we haven't met the interval time limit
71         NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
72         if (interval > 0) {
73                 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
74                 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
75                 return;
76         }
77         
78         if (!_handshakeCompleted) {
79                 NSString *version = [[[NSBundle bundleWithPath:[[NSWorkspace sharedWorkspace] fullPathForApplication:@"iTunes.app"]] infoDictionary] objectForKey:@"CFBundleVersion"], *user = @"Tristrex";
80                 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=tst&v=%@&u=%@", version, user]];
81                 
82                 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
83                 _responseData = [[NSMutableData alloc] init];
84                 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30] delegate:self];
85         }
86 }
87
88 - (BOOL)handshakeCompleted
89 {
90         return _handshakeCompleted;
91 }
92
93 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
94 {
95         ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
96         NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
97                                                                                                                                                 @"title",
98                                                                                                                                                 artist,
99                                                                                                                                                 @"artist",
100                                                                                                                                                 (album == nil) ? @"" : album,
101                                                                                                                                                 @"album",
102                                                                                                                                                 [NSString stringWithFormat:@"%i", length],
103                                                                                                                                                 @"length",
104                                                                                                                                                 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
105                                                                                                                                                 @"time",
106                                                                                                                                                 nil, nil];
107         [_tracks addObject:newTrack];
108         [self submitTracks];
109 }
110
111 - (void)submitTracks
112 {
113         if (!_handshakeCompleted) {
114                 [self attemptHandshake];
115                 return;
116         }
117         
118         NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
119         if (interval > 0) {
120                 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
121                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
122                 return;
123         }
124         
125         int i;
126         NSMutableString *requestString;
127         NSString *authString, *responseHash = @"";
128         NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
129         char *pass = (char *)[[PreferencesController getKeychainItemPasswordForUser:user] UTF8String];
130         unsigned char *buffer;
131         EVP_MD_CTX ctx;
132         
133         ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
134         
135         if ([_tracks count] == 0) {
136                 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
137                 return;
138         }
139         
140         //Build the MD5 response string we send along with the request
141         buffer = malloc(EVP_MD_size(EVP_md5()));
142         EVP_DigestInit(&ctx, EVP_md5());
143         EVP_DigestUpdate(&ctx, pass, strlen(pass));
144         EVP_DigestFinal(&ctx, buffer, NULL);
145         
146         for (i = 0; i < 16; i++) {
147                 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
148         }
149         
150         free(buffer);
151         buffer = malloc(EVP_MD_size(EVP_md5()));
152         char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
153         EVP_DigestInit(&ctx, EVP_md5());
154         EVP_DigestUpdate(&ctx, cat, strlen(cat));
155         EVP_DigestFinal(&ctx, buffer, NULL);
156         
157         responseHash = @"";
158         for (i = 0; i < 16; i++) {
159                 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
160         }
161         free(buffer);
162         
163         authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
164         requestString = [[NSMutableString alloc] initWithString:authString];
165         [authString release];
166         
167         //We can only submit ten tracks at a time
168         for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
169                 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
170                 NSString *trackString;
171                 
172                 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);
173                 [requestString appendString:trackString];
174                 [trackString release];
175         }
176         
177         //Create and send the request
178         NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30] mutableCopy];
179         [request setHTTPMethod:@"POST"];
180         [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
181         _currentStatus = AudioscrobblerSubmittingTracksStatus;
182         _responseData = [[NSMutableData alloc] init];
183         [NSURLConnection connectionWithRequest:request delegate:self];
184         [requestString release];
185         [request release];
186         
187         //If we have tracks left, submit again after the interval seconds
188 }
189
190 - (void)handleAudioscrobblerNotification:(NSNotification *)note
191 {
192         if ([[note name] isEqualToString:@"AudioscrobblerHandshakeComplete"]) {
193                 if ([_tracks count] > 0) {
194                         [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
195                 }
196         }
197 }
198
199 #pragma mark -
200
201 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
202 {
203         ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
204 }
205
206 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
207 {
208         [_responseData appendData:data];
209 }
210
211 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
212 {
213         NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
214         NSArray *lines = [string componentsSeparatedByString:@"\n"];
215         NSString *responseAction = nil;
216         
217         if ([lines count] > 0) {
218                 responseAction = [lines objectAtIndex:0];
219         }
220         
221         if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
222                 if ([lines count] < 2) {
223                         //We have a protocol error
224                 }
225                 if ([responseAction isEqualToString:@"UPTODATE"]) {
226                         if ([lines count] >= 4) {
227                                 _md5Challenge = [[lines objectAtIndex:1] retain];
228                                 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
229                                 _handshakeCompleted = YES;
230                                 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
231                         } else {
232                                 //We have a protocol error
233                         }
234                         //Something
235                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"]) {
236                         //Something plus update action
237                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
238                         //We have a error
239                 } else if ([responseAction isEqualToString:@"BADUSER"]) {
240                         //We have a bad user
241                 } else {
242                         //We have a protocol
243                 }
244         } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
245                 if ([responseAction isEqualToString:@"OK"]) {
246                 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
247                         //Bad auth
248                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
249                         //Failed
250                 }
251         }
252         
253         //Handle the final INTERVAL response
254         if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
255                 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
256                 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
257                 [_delayDate release];
258                 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
259         } else {
260                 ITDebugLog(@"No interval response.");
261                 //We have a protocol error
262         }
263         
264         [string release];
265         [_responseData release];
266 }
267
268 @end