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