Now properly escaping all strings so ampersands now submit. Added a couple of NSLogs...
[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 @"tst"
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:nil object:self];
50         }
51         return self;
52 }
53
54 - (void)dealloc
55 {
56         [_md5Challenge release];
57         [_postURL release];
58         [_responseData release];
59         [_submitTracks release];
60         [_tracks release];
61         [_delayDate release];
62         [super dealloc];
63 }
64
65 - (void)attemptHandshake
66 {
67         [self attemptHandshake:NO];
68 }
69
70 - (void)attemptHandshake:(BOOL)force
71 {
72         if (_handshakeCompleted && !force) {
73                 return;
74         }
75         
76         //Delay if we haven't met the interval time limit
77         NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
78         if (interval > 0) {
79                 ITDebugLog(@"Audioscrobbler: Delaying handshake attempt for %i seconds", interval);
80                 [self performSelector:@selector(attemptHandshake) withObject:nil afterDelay:interval + 1];
81                 return;
82         }
83         
84         NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"];
85         if (!_handshakeCompleted && user) {
86                 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://post.audioscrobbler.com/?hs=true&p=1.1&c=%@&v=%@&u=%@", AUDIOSCROBBLER_ID, AUDIOSCROBBLER_VERSION, user]];
87                 
88                 _currentStatus = AudioscrobblerRequestingHandshakeStatus;
89                 _responseData = [[NSMutableData alloc] init];
90                 [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] delegate:self];
91         }
92 }
93
94 - (BOOL)handshakeCompleted
95 {
96         return _handshakeCompleted;
97 }
98
99 - (void)submitTrack:(NSString *)title artist:(NSString *)artist album:(NSString *)album length:(int)length
100 {
101         ITDebugLog(@"Audioscrobbler: Adding a new track to the submission queue.");
102         NSDictionary *newTrack = [NSDictionary dictionaryWithObjectsAndKeys:title,
103                                                                                                                                                 @"title",
104                                                                                                                                                 artist,
105                                                                                                                                                 @"artist",
106                                                                                                                                                 (album == nil) ? @"" : album,
107                                                                                                                                                 @"album",
108                                                                                                                                                 [NSString stringWithFormat:@"%i", length],
109                                                                                                                                                 @"length",
110                                                                                                                                                 [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" timeZone:nil locale:nil],
111                                                                                                                                                 @"time",
112                                                                                                                                                 nil, nil];
113         [_tracks addObject:newTrack];
114         [self submitTracks];
115 }
116
117 - (void)submitTracks
118 {
119         if (!_handshakeCompleted) {
120                 [self attemptHandshake:NO];
121                 return;
122         }
123         
124         NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:@"audioscrobblerUser"], *passString = [PreferencesController getKeychainItemPasswordForUser:user];
125         char *pass = (char *)[passString UTF8String];
126         
127         if (passString == nil) {
128                 ITDebugLog(@"Audioscrobbler: Access denied to user password");
129                 return;
130         }
131         
132         NSTimeInterval interval = [_delayDate timeIntervalSinceNow];
133         if (interval > 0) {
134                 ITDebugLog(@"Audioscrobbler: Delaying track submission for %f seconds", interval);
135                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:interval + 1];
136                 return;
137         }
138         
139         int i;
140         NSMutableString *requestString;
141         NSString *authString, *responseHash = @"";
142         unsigned char *buffer;
143         EVP_MD_CTX ctx;
144         
145         ITDebugLog(@"Audioscrobbler: Submitting queued tracks");
146         
147         if ([_tracks count] == 0) {
148                 ITDebugLog(@"Audioscrobbler: No queued tracks to submit.");
149                 return;
150         }
151         
152         //Build the MD5 response string we send along with the request
153         buffer = malloc(EVP_MD_size(EVP_md5()));
154         EVP_DigestInit(&ctx, EVP_md5());
155         EVP_DigestUpdate(&ctx, pass, strlen(pass));
156         EVP_DigestFinal(&ctx, buffer, NULL);
157         
158         for (i = 0; i < 16; i++) {
159                 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
160         }
161         
162         free(buffer);
163         buffer = malloc(EVP_MD_size(EVP_md5()));
164         char *cat = (char *)[[responseHash stringByAppendingString:_md5Challenge] UTF8String];
165         EVP_DigestInit(&ctx, EVP_md5());
166         EVP_DigestUpdate(&ctx, cat, strlen(cat));
167         EVP_DigestFinal(&ctx, buffer, NULL);
168         
169         responseHash = @"";
170         for (i = 0; i < 16; i++) {
171                 responseHash = [responseHash stringByAppendingFormat:@"%0.2x", buffer[i]];
172         }
173         free(buffer);
174         
175         authString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSString stringWithFormat:@"u=%@&s=%@", user, responseHash], NULL, NULL, kCFStringEncodingUTF8);
176         requestString = [[NSMutableString alloc] initWithString:authString];
177         [authString release];
178         
179         //We can only submit ten tracks at a time
180         for (i = 0; (i < [_tracks count]) && (i < 10); i++) {
181                 NSDictionary *nextTrack = [_tracks objectAtIndex:i];
182                 NSString *artistEscaped, *titleEscaped, *albumEscaped, *timeEscaped, *ampersand = @"&";
183                 
184                 //Escape each of the individual parameters we're sending
185                 artistEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"artist"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
186                 titleEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"title"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
187                 albumEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"album"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
188                 timeEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[nextTrack objectForKey:@"time"], NULL, (CFStringRef)ampersand, kCFStringEncodingUTF8);
189                 
190                 [requestString appendString:[NSString stringWithFormat:@"&a[%i]=%@&t[%i]=%@&b[%i]=%@&m[%i]=&l[%i]=%@&i[%i]=%@", i, artistEscaped,
191                                                                                                                                                                                                                                                 i, titleEscaped,
192                                                                                                                                                                                                                                                 i, albumEscaped,
193                                                                                                                                                                                                                                                 i,
194                                                                                                                                                                                                                                                 i, [nextTrack objectForKey:@"length"],
195                                                                                                                                                                                                                                                 i, timeEscaped]];
196                 
197                 //Release the escaped strings
198                 [artistEscaped release];
199                 [titleEscaped release];
200                 [albumEscaped release];
201                 [timeEscaped release];
202                 
203                 [_submitTracks addObject:nextTrack];
204         }
205         
206         ITDebugLog(@"Audioscrobbler: Sending track submission request");
207         
208         //Create and send the request
209         NSMutableURLRequest *request = [[NSURLRequest requestWithURL:_postURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15] mutableCopy];
210         NSLog(@"Posting Audioscrobbler URL request: %@", requestString);
211         [request setHTTPMethod:@"POST"];
212         [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
213         _currentStatus = AudioscrobblerSubmittingTracksStatus;
214         _responseData = [[NSMutableData alloc] init];
215         [NSURLConnection connectionWithRequest:request delegate:self];
216         [requestString release];
217         [request release];
218         
219         //If we have tracks left, submit again after the interval seconds
220 }
221
222 - (void)handleAudioscrobblerNotification:(NSNotification *)note
223 {
224         if ([[note name] isEqualToString:@"AudioscrobblerHandshakeComplete"]) {
225                 if ([_tracks count] > 0) {
226                         [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
227                 }
228         }
229 }
230
231 #pragma mark -
232
233 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
234 {
235         ITDebugLog(@"Audioscrobbler: Connection error \"%@\"", error);
236 }
237
238 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
239 {
240         [_responseData appendData:data];
241 }
242
243 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
244 {
245         NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
246         NSArray *lines = [string componentsSeparatedByString:@"\n"];
247         NSString *responseAction = nil;
248         
249         if ([lines count] > 0) {
250                 responseAction = [lines objectAtIndex:0];
251         }
252         ITDebugLog(@"Audioscrobbler: Response %@", string);
253         NSLog(@"Audioscrobbler: Response %@", string);
254         if (_currentStatus == AudioscrobblerRequestingHandshakeStatus) {
255                 if ([lines count] < 2) {
256                         //We have a protocol error
257                 }
258                 if ([responseAction isEqualToString:@"UPTODATE"] || (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"UPDATE"])) {
259                         if ([lines count] >= 4) {
260                                 _md5Challenge = [[lines objectAtIndex:1] retain];
261                                 _postURL = [[NSURL alloc] initWithString:[lines objectAtIndex:2]];
262                                 _handshakeCompleted = YES;
263                                 [[NSNotificationCenter defaultCenter] postNotificationName:@"AudioscrobblerHandshakeComplete" object:self];
264                         } else {
265                                 //We have a protocol error
266                         }
267                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
268                         ITDebugLog(@"Audioscrobbler: Handshake failed (%@)", [responseAction substringFromIndex:6]);
269                         //We have a error
270                 } else if ([responseAction isEqualToString:@"BADUSER"]) {
271                         ITDebugLog(@"Audioscrobbler: Bad user name");
272                         //We have a bad user
273                 } else {
274                         ITDebugLog(@"Audioscrobbler: Handshake failed, protocol error");
275                         //We have a protocol error
276                 }
277         } else if (_currentStatus == AudioscrobblerSubmittingTracksStatus) {
278                 if ([responseAction isEqualToString:@"OK"]) {
279                         ITDebugLog(@"Audioscrobbler: Submission successful, clearing queue.");
280                         [_tracks removeObjectsInArray:_submitTracks];
281                         [_submitTracks removeAllObjects];
282                         if ([_tracks count] > 0) {
283                                 ITDebugLog(@"Audioscrobbler: Tracks remaining in queue, submitting remaining tracks");
284                                 [self performSelector:@selector(submitTracks) withObject:nil afterDelay:2];
285                         }
286                 } else if ([responseAction isEqualToString:@"BADAUTH"]) {
287                         ITDebugLog(@"Audioscrobbler: Bad password");
288                         //Bad auth
289                 } else if (([responseAction length] > 5) && [[responseAction substringToIndex:5] isEqualToString:@"FAILED"]) {
290                         ITDebugLog(@"Audioscrobbler: Submission failed (%@)", [responseAction substringFromIndex:6]);
291                         //Failed
292                 }
293         }
294         
295         //Handle the final INTERVAL response
296         if (([[lines objectAtIndex:[lines count] - 2] length] > 9) && [[[lines objectAtIndex:[lines count] - 2] substringToIndex:8] isEqualToString:@"INTERVAL"]) {
297                 int seconds = [[[lines objectAtIndex:[lines count] - 2] substringFromIndex:9] intValue];
298                 ITDebugLog(@"Audioscrobbler: INTERVAL %i", seconds);
299                 [_delayDate release];
300                 _delayDate = [[NSDate dateWithTimeIntervalSinceNow:seconds] retain];
301         } else {
302                 ITDebugLog(@"No interval response.");
303                 //We have a protocol error
304         }
305         
306         [string release];
307         [_responseData release];
308 }
309
310 @end