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