This repository has been archived by the owner on Jun 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LastifyLastfmClient.m
539 lines (429 loc) · 15.6 KB
/
LastifyLastfmClient.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//
// LastifyLastfmClient.m
// Lastify
//
// Created by George on 16/01/2009.
// Copyright 2008 George Brocklehurst. Some rights reserved (see accompanying LICENSE file for details).
//
#import "LastifyLastfmClient.h"
#import "NSString+Lastify.h"
#import "LastifyController.h"
@interface LastifyLastfmClient (Private)
- (NSString*)requestAuthToken;
- (NSString*)callMethod:(NSString*)methodName withParams:(NSDictionary*)params usingPost:(BOOL)post error:(NSError**)error;
- (void)loadSessionKey;
- (void)storeSessionKey;
@end
@implementation LastifyLastfmClient
@synthesize
APIKey,
APISecret,
authToken,
sessionKey,
waitingForUserAuth,
sessionReady,
username;
- (id)initWithAPIKey:(NSString*)newAPIKey APISecret:(NSString*)newAPISecret
{
self = [super init];
if(!self)
return nil;
self.APIKey = newAPIKey;
self.APISecret = newAPISecret;
sessionReady = FALSE;
waitingForUserAuth = FALSE;
return self;
}
- (void)dealloc
{
[APIKey release], APIKey = nil;
[APISecret release], APISecret = nil;
[authToken release], authToken = nil;
[sessionKey release], sessionKey = nil;
[username release], username = nil;
[super dealloc];
}
- (void)loadSessionKey
{
SecKeychainSearchRef search;
SecKeychainItemRef item;
SecKeychainAttributeList list;
SecKeychainAttribute attributes[3];
OSErr result;
attributes[0].tag = kSecAccountItemAttr;
attributes[0].data = (void*)[self.APIKey UTF8String];
attributes[0].length = [self.APIKey length];
NSString *itemDescription = @"Lastify Last.fm session information";
attributes[1].tag = kSecDescriptionItemAttr;
attributes[1].data = (void*)[itemDescription UTF8String];
attributes[1].length = [itemDescription length];
NSString *itemLabel = @"Lastify Last.fm session information";
attributes[2].tag = kSecLabelItemAttr;
attributes[2].data = (void*)[itemLabel UTF8String];
attributes[2].length = [itemLabel length];
list.count = 3;
list.attr = (SecKeychainAttribute*)&attributes;
result = SecKeychainSearchCreateFromAttributes(NULL, kSecGenericPasswordItemClass, &list, &search);
if(result != noErr)
return;
if(SecKeychainSearchCopyNext(search, &item) == noErr)
{
UInt32 length;
char *password = NULL;
OSStatus status;
status = SecKeychainItemCopyContent(item, NULL, NULL, &length, (void **)&password);
if(status == noErr)
{
if (password != NULL)
{
char passwordBuffer[length+1];
strncpy(passwordBuffer, password, length);
passwordBuffer[length] = '\0';
NSString *rawLoadedPassword = [NSString stringWithUTF8String:passwordBuffer];
NSArray *parts = [rawLoadedPassword componentsSeparatedByString:@" / "];
if(parts && [parts count] == 2)
{
self.sessionKey = [parts objectAtIndex:0];
self.username = [parts objectAtIndex:1];
self.waitingForUserAuth = FALSE;
self.sessionReady = TRUE;
}
}
SecKeychainItemFreeContent(NULL, password);
}
CFRelease(item);
CFRelease (search);
}
}
- (void)storeSessionKey
{
// Create attributes array
SecKeychainAttribute attributes[3];
// Set the account name (uses the application's consumer key)
attributes[0].tag = kSecAccountItemAttr;
attributes[0].data = (void*)[self.APIKey UTF8String];
attributes[0].length = [self.APIKey length];
// Set the description
NSString *itemDescription = @"Lastify Last.fm session information";
attributes[1].tag = kSecDescriptionItemAttr;
attributes[1].data = (void*)[itemDescription UTF8String];
attributes[1].length = [itemDescription length];
// Label the item
NSString *itemLabel = @"Lastify Last.fm session information";
attributes[2].tag = kSecLabelItemAttr;
attributes[2].data = (void*)[itemLabel UTF8String];
attributes[2].length = [itemLabel length];
// Create list from attributes array
SecKeychainAttributeList list;
list.count = 3;
list.attr = attributes;
// Store the password
NSString *password = [NSString stringWithFormat:@"%@ / %@", self.sessionKey, self.username];
SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, &list, [password length], [password UTF8String], NULL,NULL,NULL);
}
- (void)authenticateQuietly
{
[self loadSessionKey];
[[LastifyController sharedInstance] loadUserInterface];
}
- (void)authenticate
{
// Attempt to authenticate without user interaction
[self authenticateQuietly];
if(self.sessionKey)
return;
// We need the user to authenticate
NSString *newAuthToken = [self requestAuthToken];
if(!newAuthToken)
{
//TODO: Present an error to the user
return;
}
self.authToken = newAuthToken;
// Get the user to authorise the token
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.last.fm/api/auth/?api_key=%@&token=%@", self.APIKey, newAuthToken]]];
self.waitingForUserAuth = TRUE;
// The authentication will resume with startNewSession when the user has logged in ...
}
- (void)startNewSession
{
NSError *err = nil;
NSString *response = [self callMethod:@"auth.getSession" withParams:[NSDictionary dictionaryWithObjectsAndKeys:self.authToken, @"token", nil] usingPost:FALSE error:&err];
if(err || !response)
{
switch([err code])
{
case 15: // This token has expired
case 4: // Invalid authentication token supplied
case 14: // This token has not been authorized
case 2: // Invalid service -This service does not exist
case 3: // Invalid Method - No method with that name in this package
case 5: // Invalid format - This service doesn't exist in that format
case 6: // Invalid parameters - Your request is missing a required parameter
case 7: // Invalid resource specified
case 9: // Invalid session key - Please re-authenticate
case 10: // Invalid API key - You must be granted a valid key by last.fm
case 11: // Service Offline - This service is temporarily offline. Try again later.
case 12: // Subscribers Only - This service is only available to paid last.fm subscribers
default:
break;
}
return;
}
// Extract the username and the session key
NSString *newSessionKey = nil;
NSString *newUsername = nil;
NSScanner *scanner = [NSScanner scannerWithString:response];
[scanner scanUpToString:@"<name>" intoString:NULL];
[scanner scanString:@"<name>" intoString:NULL];
[scanner scanUpToString:@"</name>" intoString:&newUsername];
[scanner scanUpToString:@"<key>" intoString:NULL];
[scanner scanString:@"<key>" intoString:NULL];
[scanner scanUpToString:@"</key>" intoString:&newSessionKey];
if(!newSessionKey)
{
//TODO: Handle this (must be an unexpected error if not caught sooner)
return;
}
self.sessionKey = newSessionKey;
self.username = newUsername;
self.waitingForUserAuth = FALSE;
self.sessionReady = TRUE;
[self storeSessionKey];
}
- (NSString*)requestAuthToken
{
// Request a new auth token from the Last.fm server
NSError *downloadError = nil;
NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://ws.audioscrobbler.com/2.0/?method=auth.gettoken&api_key=%@", self.APIKey]] encoding:NSUTF8StringEncoding error:&downloadError];
if(downloadError || !response)
{
NSLog(@"LASTIFY failed to get Auth Token: %@", downloadError);
return nil;
}
NSString *newAuthToken = nil;
NSScanner *scanner = [NSScanner scannerWithString:response];
[scanner scanUpToString:@"<token>" intoString:NULL];
[scanner scanString:@"<token>" intoString:NULL];
[scanner scanUpToString:@"</token>" intoString:&newAuthToken];
return [[[NSString alloc] initWithString:newAuthToken] autorelease];
}
- (NSString*)callMethod:(NSString*)methodName withParams:(NSDictionary*)params usingPost:(BOOL)post error:(NSError**)error
{
NSMutableString *urlString = [NSMutableString stringWithString:@"http://ws.audioscrobbler.com/2.0/"];
// Add the standard parameters (methodName, APIKey)
NSMutableDictionary *mutableParams = [params mutableCopy];
[mutableParams setObject:self.APIKey forKey:@"api_key"];
[mutableParams setObject:methodName forKey:@"method"];
// If we have a session key, add it to the parameters
if(sessionKey)
[mutableParams setObject:sessionKey forKey:@"sk"];
// Sort the params alphabetically
NSArray *sortedKeys = [[mutableParams allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
// Add the parameters to the signature base and the URL string
NSMutableString *signatureBase = [NSMutableString stringWithCapacity:50];
NSMutableString *queryString = [NSMutableString stringWithCapacity:50];
NSEnumerator *paramEnumerator = [sortedKeys objectEnumerator];
NSString *key, *value, *escapedValue;
while(key = [paramEnumerator nextObject])
{
value = [mutableParams objectForKey:key];
[signatureBase appendFormat:@"%@%@", key, value];
escapedValue = (NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)value, NULL, (CFStringRef)@"&=:/,", kCFStringEncodingUTF8);
[queryString appendFormat:@"%@=%@&", key, escapedValue];
CFRelease(escapedValue), escapedValue = nil;
}
// Generate the signature
[signatureBase appendString:self.APISecret];
[queryString appendFormat:@"api_sig=%@", [signatureBase MD5Hash]];
// Tidy up
[mutableParams release], mutableParams = nil;
// Build the request
NSURLRequest *urlReq;
if(post)
{
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[postRequest setHTTPMethod:@"POST"];
[postRequest setHTTPBody:[queryString dataUsingEncoding:NSUTF8StringEncoding]];
urlReq = postRequest;
}
else
{
[urlString appendFormat:@"?%@", queryString];
urlReq = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
}
// Call the Last.fm API
NSHTTPURLResponse *downloadResponse;
NSError *downloadError = nil;
NSData *downloadData = nil;
downloadData = [NSURLConnection sendSynchronousRequest:urlReq returningResponse:&downloadResponse error:&downloadError];
// Check for errors in the response
if(downloadError)
{
NSLog(@"LASTIFY download error: %@", downloadError);
*error = downloadError;
return nil;
}
if([downloadResponse statusCode] != 200)
{
NSLog(@"LASTIFY bad HTTP response: %d", [downloadResponse statusCode]);
if(downloadData)
{
NSString *errorResponse = [[NSString alloc] initWithData:downloadData encoding:NSUTF8StringEncoding];
NSInteger errNo;
NSString *errMsg = nil;
NSScanner *errScanner = [NSScanner scannerWithString:errorResponse];
[errScanner scanUpToString:@"<error code=\"" intoString:NULL];
[errScanner scanString:@"<error code=\"" intoString:NULL];
[errScanner scanInteger:&errNo];
[errScanner scanUpToString:@">" intoString:NULL];
[errScanner scanString:@">" intoString:NULL];
[errScanner scanUpToString:@"</error>" intoString:&errMsg];
if(errMsg && errNo)
{
*error = [NSError
errorWithDomain:@"com.georgebrock.lastify"
code:errNo
userInfo:[NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]];
}
[errorResponse release], errorResponse = nil;
}
return nil;
}
// Extract the string from the response
NSString *response = [[NSString alloc] initWithData:downloadData encoding:NSUTF8StringEncoding];
NSLog(@"LASTIFY response: %@", response);
return [response autorelease];
}
- (BOOL)loveTrack:(NSString*)trackName byArtist:(NSString*)artistName
{
if(!self.sessionKey)
return FALSE;
NSDictionary *callParams = [NSDictionary dictionaryWithObjectsAndKeys:
trackName, @"track",
artistName, @"artist",
nil];
NSError *loveError = nil;
[self callMethod:@"track.love" withParams:callParams usingPost:TRUE error:&loveError];
return !loveError;
}
- (BOOL)banTrack:(NSString*)trackName byArtist:(NSString*)artistName
{
if(!self.sessionKey)
return FALSE;
NSDictionary *callParams = [NSDictionary dictionaryWithObjectsAndKeys:
trackName, @"track",
artistName, @"artist",
nil];
NSError *banError = nil;
[self callMethod:@"track.ban" withParams:callParams usingPost:TRUE error:&banError];
return !banError;
}
- (NSArray*)getTagsForTrack:(NSString*)trackName byArtist:(NSString*)artistName
{
if(!self.sessionKey)
return nil;
NSDictionary *callParams = [NSDictionary dictionaryWithObjectsAndKeys:
trackName, @"track",
artistName, @"artist",
nil];
NSString *response = [self callMethod:@"track.gettags" withParams:callParams usingPost:FALSE error:NULL];
if(!response)
return nil;
NSMutableArray *tags = [NSMutableArray arrayWithCapacity:1];
NSString *newTag = nil;
NSScanner *scanner = [NSScanner scannerWithString:response];
while([scanner scanUpToString:@"<name>" intoString:NULL])
{
[scanner scanString:@"<name>" intoString:NULL];
if([scanner scanUpToString:@"</name>" intoString:&newTag])
[tags addObject:newTag];
}
return (NSArray*)tags;
}
- (BOOL)addTags:(NSArray*)tags toTrack:(NSString*)trackName byArtist:(NSString*)artistName
{
if(!self.sessionKey)
return FALSE;
if([tags count] > 10)
{
NSArray *remainder = [tags subarrayWithRange:NSMakeRange(10, [tags count]-10)];
[self addTags:remainder toTrack:trackName byArtist:artistName];
tags = [tags subarrayWithRange:NSMakeRange(0, 10)];
}
NSString *tagString = [tags componentsJoinedByString:@","];
NSDictionary *callParams = [NSDictionary dictionaryWithObjectsAndKeys:
trackName, @"track",
artistName, @"artist",
tagString, @"tags",
nil];
NSError *tagError = nil;
[self callMethod:@"track.addtags" withParams:callParams usingPost:TRUE error:&tagError];
return !tagError;
}
- (BOOL)removeTags:(NSArray*)tags fromTrack:(NSString*)trackName byArtist:(NSString*)artistName
{
if(!self.sessionKey)
return FALSE;
NSString *tag;
NSDictionary *callParams;
NSEnumerator *tagEnum = [tags objectEnumerator];
BOOL result = TRUE;
while(tag = [tagEnum nextObject])
{
callParams = [NSDictionary dictionaryWithObjectsAndKeys:
trackName, @"track",
artistName, @"artist",
tag, @"tag",
nil];
NSError *tagError = nil;
[self callMethod:@"track.removetag" withParams:callParams usingPost:TRUE error:&tagError];
result = result && !tagError;
}
return result;
}
- (NSArray*)getPlaylists
{
if(!self.sessionKey)
return nil;
NSDictionary *callParams = [NSDictionary dictionaryWithObjectsAndKeys:
self.username, @"user",
nil];
NSString *response = [self callMethod:@"user.getPlaylists" withParams:callParams usingPost:FALSE error:NULL];
if(!response)
return nil;
NSMutableArray *playlists = [NSMutableArray arrayWithCapacity:1];
NSScanner *scanner = [NSScanner scannerWithString:response];
while([scanner scanUpToString:@"<playlist>" intoString:NULL])
{
NSString *playlistID = nil;
[scanner scanUpToString:@"<id>" intoString:NULL];
[scanner scanString:@"<id>" intoString:NULL];
BOOL foundID = [scanner scanUpToString:@"</id>" intoString:&playlistID];
NSString *playlistTitle = nil;
[scanner scanUpToString:@"<title>" intoString:NULL];
[scanner scanString:@"<title>" intoString:NULL];
BOOL foundTitle = [scanner scanUpToString:@"</title>" intoString:&playlistTitle];
[scanner scanUpToString:@"</playlist>" intoString:NULL];
if(foundID && foundTitle)
[playlists addObject:[NSDictionary dictionaryWithObjectsAndKeys:
playlistID, @"id",
playlistTitle, @"title",
nil]];
}
return (NSArray*)playlists;
}
- (BOOL)addTrack:(NSString*)trackName byArtist:(NSString*)artistName toPlaylist:(NSString*)playlistID
{
if(!self.sessionKey)
return FALSE;
NSDictionary *callParams = [NSDictionary dictionaryWithObjectsAndKeys:
trackName, @"track",
artistName, @"artist",
playlistID, @"playlistID",
nil];
NSError *listError = nil;
[self callMethod:@"playlist.addTrack" withParams:callParams usingPost:TRUE error:&listError];
return !listError;
}
@end