-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestObjectC.m
793 lines (642 loc) · 30.8 KB
/
testObjectC.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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
//
// ObjectiveFlickr.m
//
// Copyright (c) 2006-2014 Lukhnos D. Liu (http://lukhnos.org)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#import "ObjectiveFlickr.h"
#import "OFUtilities.h"
#import "OFXMLMapper.h"
// Test the configuration of the objective c. extension is *.m file
NSString *const OFFlickrSmallSquareSize = @"s";
NSString *const OFFlickrLargeSquareSize = @"q";
NSString *const OFFlickrThumbnailSize = @"t";
NSString *const OFFlickrSmallSize = @"m";
NSString *const OFFlickrSmallSize320 = @"n";
NSString *const OFFlickrMediumSize = nil;
NSString *const OFFlickrMediumSquareSize640 = @"z";
NSString *const OFFlickrMediumSquareSize800 = @"c";
NSString *const OFFlickrLargeSize = @"b";
NSString *const OFFlickrReadPermission = @"read";
NSString *const OFFlickrWritePermission = @"write";
NSString *const OFFlickrDeletePermission = @"delete";
NSString *const OFFlickrUploadTempFilenamePrefix = @"org.lukhnos.ObjectiveFlickr.upload";
NSString *const OFFlickrAPIReturnedErrorDomain = @"com.flickr";
NSString *const OFFlickrAPIRequestErrorDomain = @"org.lukhnos.ObjectiveFlickr";
NSString *const OFFlickrAPIRequestOAuthErrorUserInfoKey = @"OAuthError";
NSString *const OFFetchOAuthRequestTokenSession = @"FetchOAuthRequestToken";
NSString *const OFFetchOAuthAccessTokenSession = @"FetchOAuthAccessToken";
static NSString *const kEscapeChars = @"`~!@#$^&*()=+[]\\{}|;':\",/<>?";
static NSString *const kDefaultFlickrRESTAPIEndpoint = @"https://api.flickr.com/services/rest/";
static NSString *const kDefaultFlickrPhotoSource = @"https://staticflickr.com/";
static NSString *const kDefaultFlickrPhotoWebPageSource = @"https://www.flickr.com/photos/";
static NSString *const kDefaultFlickrAuthEndpoint = @"https://www.flickr.com/services/oauth/";
static NSString *const kDefaultFlickrUploadEndpoint = @"https://up.flickr.com/services/upload/";
static void AssertIsValidURLString(NSString *urlString)
{
NSURL *url = [NSURL URLWithString:urlString];
NSCAssert(url, @"Must be a valid URL, but was given: %@", urlString);
(void) url;
}
@interface OFFlickrAPIContext (PrivateMethods)
- (NSArray *)signedArgumentComponentsFromArguments:(NSDictionary *)inArguments useURIEscape:(BOOL)inUseEscape;
- (NSString *)signedQueryFromArguments:(NSDictionary *)inArguments;
@end
@implementation OFFlickrAPIContext
- (void)dealloc
{
[key release];
[sharedSecret release];
[authToken release];
[RESTAPIEndpoint release];
[photoSource release];
[photoWebPageSource release];
[authEndpoint release];
[uploadEndpoint release];
[oauthToken release];
[oauthTokenSecret release];
[super dealloc];
}
- (id)initWithAPIKey:(NSString *)inKey sharedSecret:(NSString *)inSharedSecret
{
if ((self = [super init])) {
key = [inKey copy];
sharedSecret = [inSharedSecret copy];
RESTAPIEndpoint = kDefaultFlickrRESTAPIEndpoint;
photoSource = kDefaultFlickrPhotoSource;
photoWebPageSource = kDefaultFlickrPhotoWebPageSource;
authEndpoint = kDefaultFlickrAuthEndpoint;
uploadEndpoint = kDefaultFlickrUploadEndpoint;
}
return self;
}
- (void)setAuthToken:(NSString *)inAuthToken
{
NSString *tmp = authToken;
authToken = [inAuthToken copy];
[tmp release];
}
- (NSString *)authToken
{
return authToken;
}
- (NSURL *)userAuthorizationURLWithRequestToken:(NSString *)inRequestToken requestedPermission:(NSString *)inPermission
{
NSString *perms = @"";
if ([inPermission length] > 0) {
perms = [NSString stringWithFormat:@"&perms=%@", inPermission];
}
NSString *URLString = [NSString stringWithFormat:@"https://www.flickr.com/services/oauth/authorize?oauth_token=%@%@", inRequestToken, perms];
return [NSURL URLWithString:URLString];
}
- (NSURL *)photoSourceURLFromDictionary:(NSDictionary *)inDictionary size:(NSString *)inSizeModifier
{
// From https://www.flickr.com/services/api/misc.urls.html, the URL is one of the following:
// * http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
// * http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
// * http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)
NSString *photoID = [inDictionary objectForKey:@"id"];
NSAssert([photoID length], nil);
NSString *secret = [inDictionary objectForKey:@"secret"];
NSAssert([secret length], nil);
NSString *server = [inDictionary objectForKey:@"server"];
NSAssert([server length], nil);
NSString *farmID = [inDictionary objectForKey:@"farm"];
NSURL *basePhotoSourceURL = [NSURL URLWithString:photoSource];
NSString *scheme = [basePhotoSourceURL scheme];
NSString *host = [basePhotoSourceURL host];
if ([farmID length]) {
host = [NSString stringWithFormat:@"farm%@.%@", farmID, host];
}
NSString *sizeSuffix = @"";
if ([inSizeModifier length]) {
sizeSuffix = [NSString stringWithFormat:@"_%@", inSizeModifier];
}
// TODO: Add originalsecret and originalformat support
NSString *formatExt = @"jpg";
// Combine the path
NSString *path = [NSString stringWithFormat:@"/%@/%@_%@%@.%@", server, photoID, secret, sizeSuffix, formatExt];
NSURL *staticURL = [[[NSURL alloc] initWithScheme:scheme host:host path:path] autorelease];
return staticURL;
}
- (NSURL *)photoWebPageURLFromDictionary:(NSDictionary *)inDictionary
{
return [NSURL URLWithString:[NSString stringWithFormat:@"%@%@/%@", photoWebPageSource, [inDictionary objectForKey:@"owner"], [inDictionary objectForKey:@"id"]]];
}
- (NSURL *)loginURLFromFrobDictionary:(NSDictionary *)inFrob requestedPermission:(NSString *)inPermission
{
NSString *frob = [[inFrob objectForKey:@"frob"] objectForKey:OFXMLTextContentKey];
NSDictionary *argDict = [frob length] ? [NSDictionary dictionaryWithObjectsAndKeys:frob, @"frob", inPermission, @"perms", nil] : [NSDictionary dictionaryWithObjectsAndKeys:inPermission, @"perms", nil];
NSString *URLString = [NSString stringWithFormat:@"%@?%@", authEndpoint, [self signedQueryFromArguments:argDict]];
return [NSURL URLWithString:URLString];
}
- (void)setRESTAPIEndpoint:(NSString *)inEndpoint
{
NSString *tmp = RESTAPIEndpoint;
RESTAPIEndpoint = [inEndpoint copy];
[tmp release];
}
- (NSString *)RESTAPIEndpoint
{
return RESTAPIEndpoint;
}
- (void)setPhotoSource:(NSString *)inSource
{
AssertIsValidURLString(inSource);
NSString *tmp = photoSource;
photoSource = [inSource copy];
[tmp release];
}
- (NSString *)photoSource
{
return photoSource;
}
- (void)setPhotoWebPageSource:(NSString *)inSource
{
AssertIsValidURLString(inSource);
NSString *tmp = photoWebPageSource;
photoWebPageSource = [inSource copy];
[tmp release];
}
- (NSString *)photoWebPageSource
{
return photoWebPageSource;
}
- (void)setAuthEndpoint:(NSString *)inEndpoint
{
NSString *tmp = authEndpoint;
authEndpoint = [inEndpoint copy];
[tmp release];
}
- (NSString *)authEndpoint
{
return authEndpoint;
}
- (void)setUploadEndpoint:(NSString *)inEndpoint
{
NSString *tmp = uploadEndpoint;
uploadEndpoint = [inEndpoint copy];
[tmp release];
}
- (NSString *)uploadEndpoint
{
return uploadEndpoint;
}
- (void)setOAuthToken:(NSString *)inToken
{
NSString *tmp = oauthToken;
oauthToken = [inToken copy];
[tmp release];
}
- (NSString *)OAuthToken
{
return oauthToken;
}
- (void)setOAuthTokenSecret:(NSString *)inSecret;
{
NSString *tmp = oauthTokenSecret;
oauthTokenSecret = [inSecret copy];
[tmp release];
}
- (NSString *)OAuthTokenSecret
{
return oauthTokenSecret;
}
@synthesize key;
@synthesize sharedSecret;
@end
@implementation OFFlickrAPIContext (PrivateMethods)
- (NSArray *)signedArgumentComponentsFromArguments:(NSDictionary *)inArguments useURIEscape:(BOOL)inUseEscape
{
NSMutableDictionary *newArgs = [NSMutableDictionary dictionaryWithDictionary:inArguments];
if ([key length]) {
[newArgs setObject:key forKey:@"api_key"];
}
if ([authToken length]) {
[newArgs setObject:authToken forKey:@"auth_token"];
}
// combine the args
NSMutableArray *argArray = [NSMutableArray array];
NSMutableString *sigString = [NSMutableString stringWithString:[sharedSecret length] ? sharedSecret : @""];
NSArray *sortedArgs = [[newArgs allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSEnumerator *argEnumerator = [sortedArgs objectEnumerator];
NSString *nextKey;
while ((nextKey = [argEnumerator nextObject])) {
NSString *value = [[newArgs objectForKey:nextKey] description];
[sigString appendFormat:@"%@%@", nextKey, value];
[argArray addObject:[NSArray arrayWithObjects:nextKey, (inUseEscape ? OFEscapedURLStringFromNSString(value) : value), nil]];
}
NSString *signature = OFMD5HexStringFromNSString(sigString);
[argArray addObject:[NSArray arrayWithObjects:@"api_sig", signature, nil]];
return argArray;
}
- (NSString *)signedQueryFromArguments:(NSDictionary *)inArguments
{
NSArray *argComponents = [self signedArgumentComponentsFromArguments:inArguments useURIEscape:YES];
NSMutableArray *args = [NSMutableArray array];
NSEnumerator *componentEnumerator = [argComponents objectEnumerator];
NSArray *nextArg;
while ((nextArg = [componentEnumerator nextObject])) {
[args addObject:[nextArg componentsJoinedByString:@"="]];
}
return [args componentsJoinedByString:@"&"];
}
- (NSDictionary *)signedOAuthHTTPQueryArguments:(NSDictionary *)inArguments baseURL:(NSURL *)inURL method:(NSString *)inMethod
{
NSMutableDictionary *newArgs = [NSMutableDictionary dictionaryWithDictionary:inArguments];
[newArgs setObject:[OFGenerateUUIDString() substringToIndex:8] forKey:@"oauth_nonce"];
[newArgs setObject:[NSString stringWithFormat:@"%lu", (long)[[NSDate date] timeIntervalSince1970]] forKey:@"oauth_timestamp"];
[newArgs setObject:@"1.0" forKey:@"oauth_version"];
[newArgs setObject:@"HMAC-SHA1" forKey:@"oauth_signature_method"];
[newArgs setObject:key forKey:@"oauth_consumer_key"];
if (![inArguments objectForKey:@"oauth_token"] && oauthToken) {
[newArgs setObject:oauthToken forKey:@"oauth_token"];
}
NSString *signatureKey = nil;
if (oauthTokenSecret) {
signatureKey = [NSString stringWithFormat:@"%@&%@", sharedSecret, oauthTokenSecret];
}
else {
signatureKey = [NSString stringWithFormat:@"%@&", sharedSecret];
}
NSMutableString *baseString = [NSMutableString string];
[baseString appendString:inMethod];
[baseString appendString:@"&"];
[baseString appendString:OFEscapedURLStringFromNSStringWithExtraEscapedChars([inURL absoluteString], kEscapeChars)];
NSArray *sortedArgKeys = [[newArgs allKeys] sortedArrayUsingSelector:@selector(compare:)];
[baseString appendString:@"&"];
NSMutableArray *baseStrArgs = [NSMutableArray array];
NSEnumerator *kenum = [sortedArgKeys objectEnumerator];
NSString *k;
while ((k = [kenum nextObject]) != nil) {
[baseStrArgs addObject:[NSString stringWithFormat:@"%@=%@", k, OFEscapedURLStringFromNSStringWithExtraEscapedChars([[newArgs objectForKey:k] description], kEscapeChars)]];
}
[baseString appendString:OFEscapedURLStringFromNSStringWithExtraEscapedChars([baseStrArgs componentsJoinedByString:@"&"], kEscapeChars)];
NSString *signature = OFHMACSha1Base64(signatureKey, baseString);
[newArgs setObject:signature forKey:@"oauth_signature"];
return newArgs;
}
- (NSURL *)oauthURLFromBaseURL:(NSURL *)inURL method:(NSString *)inMethod arguments:(NSDictionary *)inArguments
{
NSDictionary *newArgs = [self signedOAuthHTTPQueryArguments:inArguments baseURL:inURL method:inMethod];
NSMutableArray *queryArray = [NSMutableArray array];
NSEnumerator *kenum = [newArgs keyEnumerator];
NSString *k;
while ((k = [kenum nextObject]) != nil) {
[queryArray addObject:[NSString stringWithFormat:@"%@=%@", k, OFEscapedURLStringFromNSStringWithExtraEscapedChars([[newArgs objectForKey:k] description], kEscapeChars)]];
}
NSString *newURLStringWithQuery = [NSString stringWithFormat:@"%@?%@", [inURL absoluteString], [queryArray componentsJoinedByString:@"&"]];
return [NSURL URLWithString:newURLStringWithQuery];
}
@end
@interface OFFlickrAPIRequest (PrivateMethods)
- (void)cleanUpTempFile;
@end
@implementation OFFlickrAPIRequest
- (void)dealloc
{
[context release];
HTTPRequest.delegate = nil;
[HTTPRequest cancelWithoutDelegateMessage];
[HTTPRequest release];
[sessionInfo release];
[self cleanUpTempFile];
[super dealloc];
}
- (id)initWithAPIContext:(OFFlickrAPIContext *)inContext
{
if ((self = [super init])) {
context = [inContext retain];
HTTPRequest = [[LFHTTPRequest alloc] init];
[HTTPRequest setDelegate:self];
}
return self;
}
- (OFFlickrAPIContext *)context
{
return context;
}
- (OFFlickrAPIRequestDelegateType)delegate
{
return delegate;
}
- (void)setDelegate:(OFFlickrAPIRequestDelegateType)inDelegate
{
delegate = inDelegate;
}
- (id)sessionInfo
{
return [[sessionInfo retain] autorelease];
}
- (void)setSessionInfo:(id)inInfo
{
id tmp = sessionInfo;
sessionInfo = [inInfo retain];
[tmp release];
}
- (NSTimeInterval)requestTimeoutInterval
{
return [HTTPRequest timeoutInterval];
}
- (void)setRequestTimeoutInterval:(NSTimeInterval)inTimeInterval
{
[HTTPRequest setTimeoutInterval:inTimeInterval];
}
- (BOOL)isRunning
{
return [HTTPRequest isRunning];
}
- (void)cancel
{
[HTTPRequest cancelWithoutDelegateMessage];
[self cleanUpTempFile];
}
- (BOOL)fetchOAuthRequestTokenWithCallbackURL:(NSURL *)inCallbackURL
{
if ([HTTPRequest isRunning]) {
return NO;
}
NSDictionary *paramsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[inCallbackURL absoluteString], @"oauth_callback", nil];
NSURL *requestURL = [context oauthURLFromBaseURL:[NSURL URLWithString:@"https://www.flickr.com/services/oauth/request_token"] method:LFHTTPRequestGETMethod arguments:paramsDictionary];
[HTTPRequest setSessionInfo:OFFetchOAuthRequestTokenSession];
[HTTPRequest setContentType:nil];
return [HTTPRequest performMethod:LFHTTPRequestGETMethod onURL:requestURL withData:nil];
}
- (BOOL)fetchOAuthAccessTokenWithRequestToken:(NSString *)inRequestToken verifier:(NSString *)inVerifier
{
if ([HTTPRequest isRunning]) {
return NO;
}
NSDictionary *paramsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:inRequestToken, @"oauth_token", inVerifier, @"oauth_verifier", nil];
NSURL *requestURL = [context oauthURLFromBaseURL:[NSURL URLWithString:@"https://www.flickr.com/services/oauth/access_token"] method:LFHTTPRequestGETMethod arguments:paramsDictionary];
[HTTPRequest setSessionInfo:OFFetchOAuthAccessTokenSession];
[HTTPRequest setContentType:nil];
return [HTTPRequest performMethod:LFHTTPRequestGETMethod onURL:requestURL withData:nil];
}
- (BOOL)callAPIMethodWithGET:(NSString *)inMethodName arguments:(NSDictionary *)inArguments
{
if ([HTTPRequest isRunning]) {
return NO;
}
// combine the parameters
NSMutableDictionary *newArgs = inArguments ? [NSMutableDictionary dictionaryWithDictionary:inArguments] : [NSMutableDictionary dictionary];
[newArgs setObject:inMethodName forKey:@"method"];
NSURL *requestURL = nil;
if ([context OAuthToken] && [context OAuthTokenSecret]) {
requestURL = [context oauthURLFromBaseURL:[NSURL URLWithString:[context RESTAPIEndpoint]] method:LFHTTPRequestGETMethod arguments:newArgs];
}
else {
NSString *query = [context signedQueryFromArguments:newArgs];
NSString *URLString = [NSString stringWithFormat:@"%@?%@", [context RESTAPIEndpoint], query];
requestURL = [NSURL URLWithString:URLString];
}
if (requestURL) {
[HTTPRequest setContentType:nil];
return [HTTPRequest performMethod:LFHTTPRequestGETMethod onURL:requestURL withData:nil];
}
return NO;
}
static NSData *NSDataFromOAuthPreferredWebForm(NSDictionary *formDictionary)
{
NSMutableString *combinedDataString = [NSMutableString string];
NSEnumerator *enumerator = [formDictionary keyEnumerator];
id key = [enumerator nextObject];
if (key) {
id value = [formDictionary objectForKey:key];
[combinedDataString appendString:[NSString stringWithFormat:@"%@=%@",
[(NSString*)key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
OFEscapedURLStringFromNSStringWithExtraEscapedChars([value description], kEscapeChars)]];
while ((key = [enumerator nextObject])) {
value = [formDictionary objectForKey:key];
[combinedDataString appendString:[NSString stringWithFormat:@"&%@=%@", [(NSString*)key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], OFEscapedURLStringFromNSStringWithExtraEscapedChars([value description], kEscapeChars)]];
}
}
return [combinedDataString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
}
- (BOOL)callAPIMethodWithPOST:(NSString *)inMethodName arguments:(NSDictionary *)inArguments
{
if ([HTTPRequest isRunning]) {
return NO;
}
// combine the parameters
NSMutableDictionary *newArgs = inArguments ? [NSMutableDictionary dictionaryWithDictionary:inArguments] : [NSMutableDictionary dictionary];
[newArgs setObject:inMethodName forKey:@"method"];
NSData *postData = nil;
if ([context OAuthToken] && [context OAuthTokenSecret]) {
NSDictionary *signedArgs = [context signedOAuthHTTPQueryArguments:newArgs baseURL:[NSURL URLWithString:[context RESTAPIEndpoint]] method:LFHTTPRequestPOSTMethod];
postData = NSDataFromOAuthPreferredWebForm(signedArgs);
}
else {
NSString *arguments = [context signedQueryFromArguments:newArgs];
postData = [arguments dataUsingEncoding:NSUTF8StringEncoding];
}
[HTTPRequest setContentType:LFHTTPRequestWWWFormURLEncodedContentType];
return [HTTPRequest performMethod:LFHTTPRequestPOSTMethod onURL:[NSURL URLWithString:[context RESTAPIEndpoint]] withData:postData];
}
- (BOOL)uploadImageStream:(NSInputStream *)inImageStream suggestedFilename:(NSString *)inFilename MIMEType:(NSString *)inType arguments:(NSDictionary *)inArguments
{
if ([HTTPRequest isRunning]) {
return NO;
}
// get the api_sig
NSArray *argComponents = nil;
if ([context OAuthToken] && [context OAuthTokenSecret]) {
NSMutableArray *newArgsComps = [NSMutableArray array];
NSDictionary *signedArgs = [context signedOAuthHTTPQueryArguments:(inArguments ? inArguments : [NSDictionary dictionary]) baseURL:[NSURL URLWithString:[context uploadEndpoint]] method:LFHTTPRequestPOSTMethod];
NSEnumerator *keyEnum = [signedArgs keyEnumerator];
NSString *key;
while ((key = [keyEnum nextObject]) != nil) {
NSString *value = [signedArgs valueForKey:key];
[newArgsComps addObject:[NSArray arrayWithObjects:key, value, nil]];
}
argComponents = newArgsComps;
}
else if ([[context authToken] length] > 0) {
argComponents = [[self context] signedArgumentComponentsFromArguments:(inArguments ? inArguments : [NSDictionary dictionary]) useURIEscape:NO];
}
else {
return NO;
}
NSString *separator = OFGenerateUUIDString();
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", separator];
// build the multipart form
NSMutableString *multipartBegin = [NSMutableString string];
NSMutableString *multipartEnd = [NSMutableString string];
NSEnumerator *componentEnumerator = [argComponents objectEnumerator];
NSArray *nextArgComponent;
while ((nextArgComponent = [componentEnumerator nextObject])) {
[multipartBegin appendFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n", separator, [nextArgComponent objectAtIndex:0], [nextArgComponent objectAtIndex:1]];
}
// add filename, if nil, generate a UUID
[multipartBegin appendFormat:@"--%@\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"%@\"\r\n", separator, [inFilename length] ? inFilename : OFGenerateUUIDString()];
[multipartBegin appendFormat:@"Content-Type: %@\r\n\r\n", inType];
[multipartEnd appendFormat:@"\r\n--%@--", separator];
// now we have everything, create a temp file for this purpose; although UUID is inferior to
[self cleanUpTempFile];
uploadTempFilename = [[NSTemporaryDirectory() stringByAppendingFormat:@"%@.%@", OFFlickrUploadTempFilenamePrefix, OFGenerateUUIDString()] retain];
// create the write stream
NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:uploadTempFilename append:NO];
[outputStream open];
const char *UTF8String;
size_t writeLength;
UTF8String = [multipartBegin UTF8String];
writeLength = strlen(UTF8String);
size_t __unused actualWrittenLength;
actualWrittenLength = [outputStream write:(uint8_t *)UTF8String maxLength:writeLength];
NSAssert(actualWrittenLength == writeLength, @"Must write multipartBegin");
// open the input stream
const size_t bufferSize = 65536;
size_t readSize = 0;
uint8_t *buffer = (uint8_t *)calloc(1, bufferSize);
NSAssert(buffer, @"Must have enough memory for copy buffer");
[inImageStream open];
while ([inImageStream hasBytesAvailable]) {
if (!(readSize = [inImageStream read:buffer maxLength:bufferSize])) {
break;
}
size_t __unused actualWrittenLength;
actualWrittenLength = [outputStream write:buffer maxLength:readSize];
NSAssert (actualWrittenLength == readSize, @"Must completes the writing");
}
[inImageStream close];
free(buffer);
UTF8String = [multipartEnd UTF8String];
writeLength = strlen(UTF8String);
actualWrittenLength = [outputStream write:(uint8_t *)UTF8String maxLength:writeLength];
NSAssert(actualWrittenLength == writeLength, @"Must write multipartBegin");
[outputStream close];
NSError *error = nil;
NSDictionary *fileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:uploadTempFilename error:&error];
NSAssert(fileInfo && !error, @"Must have upload temp file");
NSNumber *fileSizeNumber = [fileInfo objectForKey:NSFileSize];
NSUInteger fileSize = [fileSizeNumber integerValue];
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:uploadTempFilename];
[HTTPRequest setContentType:contentType];
return [HTTPRequest performMethod:LFHTTPRequestPOSTMethod onURL:[NSURL URLWithString:[context uploadEndpoint]] withInputStream:inputStream knownContentSize:fileSize];
}
#pragma mark LFHTTPRequest delegate methods
- (void)httpRequestDidComplete:(LFHTTPRequest *)request
{
if ([request sessionInfo] == OFFetchOAuthRequestTokenSession) {
[request setSessionInfo:nil];
NSString *response = [[[NSString alloc] initWithData:[request receivedData] encoding:NSUTF8StringEncoding] autorelease];
NSDictionary *params = OFExtractURLQueryParameter(response);
NSString *oat = [params objectForKey:@"oauth_token"];
NSString *oats = [params objectForKey:@"oauth_token_secret"];
if (!oat || !oats) {
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:response, OFFlickrAPIRequestOAuthErrorUserInfoKey, nil];
NSError *error = [NSError errorWithDomain:OFFlickrAPIRequestErrorDomain code:OFFlickrAPIRequestOAuthError userInfo:userInfo];
[delegate flickrAPIRequest:self didFailWithError:error];
}
else {
NSAssert([delegate respondsToSelector:@selector(flickrAPIRequest:didObtainOAuthRequestToken:secret:)], @"Delegate must implement the method -flickrAPIRequest:didObtainOAuthRequestToken:secret: to handle OAuth request token callback");
[delegate flickrAPIRequest:self didObtainOAuthRequestToken:oat secret:oats];
}
}
else if ([request sessionInfo] == OFFetchOAuthAccessTokenSession) {
[request setSessionInfo:nil];
NSString *response = [[[NSString alloc] initWithData:[request receivedData] encoding:NSUTF8StringEncoding] autorelease];
NSDictionary *params = OFExtractURLQueryParameter(response);
NSString *fn = [params objectForKey:@"fullname"];
NSString *oat = [params objectForKey:@"oauth_token"];
NSString *oats = [params objectForKey:@"oauth_token_secret"];
NSString *nsid = [params objectForKey:@"user_nsid"];
NSString *un = [params objectForKey:@"username"];
if (!fn || !oat || !oats || !nsid || !un) {
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:response, OFFlickrAPIRequestOAuthErrorUserInfoKey, nil];
NSError *error = [NSError errorWithDomain:OFFlickrAPIRequestErrorDomain code:OFFlickrAPIRequestOAuthError userInfo:userInfo];
[delegate flickrAPIRequest:self didFailWithError:error];
}
else {
NSAssert([delegate respondsToSelector:@selector(flickrAPIRequest:didObtainOAuthAccessToken:secret:userFullName:userName:userNSID:)], @"Delegate must implement -flickrAPIRequest:didObtainOAuthAccessToken:secret:userFullName:userName:userNSID: to handle the obtained access token");
[delegate flickrAPIRequest:self didObtainOAuthAccessToken:oat secret:oats userFullName:fn userName:un userNSID:nsid];
}
}
else {
NSDictionary *responseDictionary = [OFXMLMapper dictionaryMappedFromXMLData:[request receivedData]];
NSDictionary *rsp = [responseDictionary objectForKey:@"rsp"];
NSString *stat = [rsp objectForKey:@"stat"];
// this also fails when (responseDictionary, rsp, stat) == nil, so it's a guranteed way of checking the result
if (![stat isEqualToString:@"ok"]) {
NSDictionary *err = [rsp objectForKey:@"err"];
NSString *code = [err objectForKey:@"code"];
NSString *msg = [err objectForKey:@"msg"];
NSError *toDelegateError;
if ([code length]) {
// intValue for 10.4-compatibility
toDelegateError = [NSError errorWithDomain:OFFlickrAPIReturnedErrorDomain code:[code intValue] userInfo:[msg length] ? [NSDictionary dictionaryWithObjectsAndKeys:msg, NSLocalizedFailureReasonErrorKey, nil] : nil];
}
else {
toDelegateError = [NSError errorWithDomain:OFFlickrAPIRequestErrorDomain code:OFFlickrAPIRequestFaultyXMLResponseError userInfo:nil];
}
if ([delegate respondsToSelector:@selector(flickrAPIRequest:didFailWithError:)]) {
[delegate flickrAPIRequest:self didFailWithError:toDelegateError];
}
return;
}
[self cleanUpTempFile];
if ([delegate respondsToSelector:@selector(flickrAPIRequest:didCompleteWithResponse:)]) {
[delegate flickrAPIRequest:self didCompleteWithResponse:rsp];
}
}
}
- (void)httpRequest:(LFHTTPRequest *)request didFailWithError:(NSString *)error
{
NSError *toDelegateError = nil;
if ([error isEqualToString:LFHTTPRequestConnectionError]) {
toDelegateError = [NSError errorWithDomain:OFFlickrAPIRequestErrorDomain code:OFFlickrAPIRequestConnectionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Network connection error", NSLocalizedFailureReasonErrorKey, nil]];
}
else if ([error isEqualToString:LFHTTPRequestTimeoutError]) {
toDelegateError = [NSError errorWithDomain:OFFlickrAPIRequestErrorDomain code:OFFlickrAPIRequestTimeoutError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Request timeout", NSLocalizedFailureReasonErrorKey, nil]];
}
else {
toDelegateError = [NSError errorWithDomain:OFFlickrAPIRequestErrorDomain code:OFFlickrAPIRequestUnknownError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unknown error", NSLocalizedFailureReasonErrorKey, nil]];
}
[self cleanUpTempFile];
if ([delegate respondsToSelector:@selector(flickrAPIRequest:didFailWithError:)]) {
[delegate flickrAPIRequest:self didFailWithError:toDelegateError];
}
}
- (void)httpRequest:(LFHTTPRequest *)request sentBytes:(NSUInteger)bytesSent total:(NSUInteger)total
{
if (uploadTempFilename && [delegate respondsToSelector:@selector(flickrAPIRequest:imageUploadSentBytes:totalBytes:)]) {
[delegate flickrAPIRequest:self imageUploadSentBytes:bytesSent totalBytes:total];
}
}
@end
@implementation OFFlickrAPIRequest (PrivateMethods)
- (void)cleanUpTempFile
{
if (uploadTempFilename) {
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:uploadTempFilename]) {
BOOL __unused removeResult = NO;
NSError *error = nil;
removeResult = [fileManager removeItemAtPath:uploadTempFilename error:&error];
NSAssert(removeResult, @"Should be able to remove temp file");
}
[uploadTempFilename release];
uploadTempFilename = nil;
}
}
@end