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