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