forked from facebook/facebook-ios-sdk
/
FBRequestConnection.m
1398 lines (1192 loc) · 54.1 KB
/
FBRequestConnection.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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2012 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <UIKit/UIImage.h>
#import "FBSBJSON.h"
#import "FBError.h"
#import "FBURLConnection.h"
#import "FBRequestBody.h"
#import "FBSession.h"
#import "FBSession+Internal.h"
#import "FBSettings.h"
#import "FBRequestConnection.h"
#import "FBRequestConnection+Internal.h"
#import "FBRequest.h"
#import "Facebook.h"
#import "FBGraphObject.h"
#import "FBLogger.h"
#import "FBUtility.h"
#import "FBDataDiskCache.h"
#import "FBSDKVersion.h"
// URL construction constants
NSString *const kGraphURL = @"https://graph." FB_BASE_URL;
NSString *const kGraphBaseURL = @"https://graph." FB_BASE_URL @"/";
NSString *const kRestBaseURL = @"https://api." FB_BASE_URL @"/method/";
NSString *const kBatchKey = @"batch";
NSString *const kBatchMethodKey = @"method";
NSString *const kBatchRelativeURLKey = @"relative_url";
NSString *const kBatchAttachmentKey = @"attached_files";
NSString *const kBatchFileNamePrefix = @"file";
NSString *const kAccessTokenKey = @"access_token";
NSString *const kSDK = @"ios";
NSString *const kUserAgentBase = @"FBiOSSDK";
NSString *const kExtendTokenRestMethod = @"auth.extendSSOAccessToken";
NSString *const kBatchRestMethodBaseURL = @"method/";
// response object property/key
NSString *const FBNonJSONResponseProperty = @"FACEBOOK_NON_JSON_RESULT";
static const int kRESTAPIAccessTokenErrorCode = 190;
static const int kAPISessionNoLongerActiveErrorCode = 2500;
static const NSTimeInterval kDefaultTimeout = 180.0;
static const int kMaximumBatchSize = 50;
typedef void (^KeyValueActionHandler)(NSString *key, id value);
// ----------------------------------------------------------------------------
// Private class to store requests and their metadata.
//
@interface FBRequestMetadata : NSObject
@property (nonatomic, retain) FBRequest *request;
@property (nonatomic, copy) FBRequestHandler completionHandler;
@property (nonatomic, copy) NSString *batchEntryName;
- (id) initWithRequest:(FBRequest *)request
completionHandler:(FBRequestHandler)handler
batchEntryName:(NSString *)name;
@end
@implementation FBRequestMetadata
@synthesize batchEntryName = _batchEntryName;
@synthesize completionHandler = _completionHandler;
@synthesize request = _request;
- (id) initWithRequest:(FBRequest *)request
completionHandler:(FBRequestHandler)handler
batchEntryName:(NSString *)name {
if (self = [super init]) {
self.request = request;
self.completionHandler = handler;
self.batchEntryName = name;
}
return self;
}
- (void) dealloc {
[_request release];
[_completionHandler release];
[_batchEntryName release];
[super dealloc];
}
- (NSString*)description {
return [NSString stringWithFormat:@"<%@: %p, batchEntryName: %@, completionHandler: %p, request: %@>",
NSStringFromClass([self class]),
self,
self.batchEntryName,
self.completionHandler,
self.request.description];
}
@end
// ----------------------------------------------------------------------------
// FBRequestConnectionState
typedef enum FBRequestConnectionState {
kStateCreated,
kStateSerialized,
kStateStarted,
kStateCompleted,
kStateCancelled,
} FBRequestConnectionState;
// ----------------------------------------------------------------------------
// Private properties and methods
@interface FBRequestConnection ()
@property (nonatomic, retain) FBURLConnection *connection;
@property (nonatomic, retain) NSMutableArray *requests;
@property (nonatomic) FBRequestConnectionState state;
@property (nonatomic) NSTimeInterval timeout;
@property (nonatomic, retain) NSMutableURLRequest *internalUrlRequest;
@property (nonatomic, retain, readwrite) NSHTTPURLResponse *urlResponse;
@property (nonatomic, retain) FBRequest *deprecatedRequest;
@property (nonatomic, retain) FBLogger *logger;
@property (nonatomic) unsigned long requestStartTime;
@property (nonatomic, readonly) BOOL isResultFromCache;
- (NSMutableURLRequest *)requestWithBatch:(NSArray *)requests
timeout:(NSTimeInterval)timeout;
- (NSString *)urlStringForSingleRequest:(FBRequest *)request forBatch:(BOOL)forBatch;
- (void)appendJSONRequests:(NSArray *)requests
toBody:(FBRequestBody *)body
andNameAttachments:(NSMutableDictionary *)attachments
logger:(FBLogger *)logger;
- (void)addRequest:(FBRequestMetadata *)metadata
toBatch:(NSMutableArray *)batch
attachments:(NSDictionary *)attachments;
- (BOOL)isAttachment:(id)item;
- (void)appendAttachments:(NSDictionary *)attachments
toBody:(FBRequestBody *)body
addFormData:(BOOL)addFormData
logger:(FBLogger *)logger;
+ (void)processGraphObject:(id<FBGraphObject>)object
forPath:(NSString*)path
withAction:(KeyValueActionHandler)action;
- (void)completeWithResponse:(NSURLResponse *)response
data:(NSData *)data
orError:(NSError *)error;
- (NSArray *)parseJSONResponse:(NSData *)data
error:(NSError **)error
statusCode:(int)statusCode;
- (id)parseJSONOrOtherwise:(NSString *)utf8
error:(NSError **)error;
- (void)completeDeprecatedWithData:(NSData *)data
results:(NSArray *)results
orError:(NSError *)error;
- (void)completeWithResults:(NSArray *)results
orError:(NSError *)error;
- (NSError *)errorFromResult:(id)idResult;
- (NSError *)errorWithCode:(FBErrorCode)code
statusCode:(int)statusCode
parsedJSONResponse:(id)response
innerError:(NSError*)innerError
message:(NSString*)message;
- (NSError *)checkConnectionError:(NSError *)innerError
statusCode:(int)statusCode
parsedJSONResponse:(id)response;
- (BOOL)isInvalidSessionError:(NSError *)error
resultIndex:(int)index;
- (void)registerTokenToOmitFromLog:(NSString *)token;
- (void)addPiggybackRequests;
- (void)logRequest:(NSMutableURLRequest *)request
bodyLength:(int)bodyLength
bodyLogger:(FBLogger *)bodyLogger
attachmentLogger:(FBLogger *)attachmentLogger;
- (NSString *)getBatchAppID:(NSArray*)requests;
+ (NSString *)userAgent;
+ (void)addRequestToExtendTokenForSession:(FBSession*)session connection:(FBRequestConnection*)connection;
@end
// ----------------------------------------------------------------------------
// FBRequestConnection
@implementation FBRequestConnection
// ----------------------------------------------------------------------------
// Property implementations
@synthesize connection = _connection;
@synthesize requests = _requests;
@synthesize state = _state;
@synthesize timeout = _timeout;
@synthesize internalUrlRequest = _internalUrlRequest;
@synthesize urlResponse = _urlResponse;
@synthesize deprecatedRequest = _deprecatedRequest;
@synthesize logger = _logger;
@synthesize requestStartTime = _requestStartTime;
@synthesize isResultFromCache = _isResultFromCache;
- (NSMutableURLRequest *)urlRequest
{
if (self.internalUrlRequest) {
NSMutableURLRequest *request = self.internalUrlRequest;
[request setValue:[FBRequestConnection userAgent] forHTTPHeaderField:@"User-Agent"];
[self logRequest:request bodyLength:0 bodyLogger:nil attachmentLogger:nil];
return request;
} else {
// CONSIDER: Could move to kStateSerialized here by caching result, but
// it seems bad for a get accessor to modify state in observable manner.
return [self requestWithBatch:self.requests timeout:_timeout];
}
}
- (void)setUrlRequest:(NSMutableURLRequest *)request
{
NSAssert((self.state == kStateCreated) || (self.state == kStateSerialized),
@"Cannot set urlRequest after starting or cancelling.");
self.state = kStateSerialized;
self.internalUrlRequest = request;
}
// ----------------------------------------------------------------------------
// Lifetime
- (id)init
{
return [self initWithTimeout:kDefaultTimeout];
}
- (id)initWithTimeout:(NSTimeInterval)timeout
{
if (self = [super init]) {
_requests = [[NSMutableArray alloc] init];
_timeout = timeout;
_state = kStateCreated;
_logger = [[FBLogger alloc] initWithLoggingBehavior:FBLoggingBehaviorFBRequests];
_isResultFromCache = NO;
}
return self;
}
- (void)dealloc
{
[_connection cancel];
[_connection release];
[_requests release];
[_internalUrlRequest release];
[_urlResponse release];
[_deprecatedRequest release];
[_logger release];
[super dealloc];
}
// ----------------------------------------------------------------------------
// Public methods
- (void)addRequest:(FBRequest *)request
completionHandler:(FBRequestHandler)handler
{
[self addRequest:request completionHandler:handler batchEntryName:nil];
}
- (void)addRequest:(FBRequest *)request
completionHandler:(FBRequestHandler)handler
batchEntryName:(NSString *)name
{
NSAssert(self.state == kStateCreated,
@"Requests must be added before starting or cancelling.");
FBRequestMetadata *metadata = [[FBRequestMetadata alloc] initWithRequest:request
completionHandler:handler
batchEntryName:name];
[self.requests addObject:metadata];
[metadata release];
}
- (void)start
{
[self startWithCacheIdentity:nil
skipRoundtripIfCached:NO];
}
- (void)cancel {
// Cancelling self.connection might trigger error handlers that cause us to
// get freed. Make sure we stick around long enough to finish this method call.
[[self retain] autorelease];
[self.connection cancel];
self.connection = nil;
self.state = kStateCancelled;
}
// ----------------------------------------------------------------------------
// Public class methods
+ (FBRequestConnection*)startForMeWithCompletionHandler:(FBRequestHandler)handler {
FBRequest *request = [FBRequest requestForMe];
return [request startWithCompletionHandler:handler];
}
+ (FBRequestConnection*)startForMyFriendsWithCompletionHandler:(FBRequestHandler)handler {
FBRequest *request = [FBRequest requestForMyFriends];
return [request startWithCompletionHandler:handler];
}
+ (FBRequestConnection*)startForUploadPhoto:(UIImage *)photo
completionHandler:(FBRequestHandler)handler {
FBRequest *request = [FBRequest requestForUploadPhoto:photo];
return [request startWithCompletionHandler:handler];
}
+ (FBRequestConnection *)startForPostStatusUpdate:(NSString *)message
completionHandler:(FBRequestHandler)handler {
FBRequest *request = [FBRequest requestForPostStatusUpdate:message];
return [request startWithCompletionHandler:handler];
}
+ (FBRequestConnection *)startForPostStatusUpdate:(NSString *)message
place:(id)place
tags:(id<NSFastEnumeration>)tags
completionHandler:(FBRequestHandler)handler {
FBRequest *request = [FBRequest requestForPostStatusUpdate:message
place:place
tags:tags];
return [request startWithCompletionHandler:handler];
}
+ (FBRequestConnection*)startForPlacesSearchAtCoordinate:(CLLocationCoordinate2D)coordinate
radiusInMeters:(NSInteger)radius
resultsLimit:(NSInteger)limit
searchText:(NSString*)searchText
completionHandler:(FBRequestHandler)handler {
FBRequest *request = [FBRequest requestForPlacesSearchAtCoordinate:coordinate
radiusInMeters:radius
resultsLimit:limit
searchText:searchText];
return [request startWithCompletionHandler:handler];
}
+ (FBRequestConnection*)startWithGraphPath:(NSString*)graphPath
completionHandler:(FBRequestHandler)handler
{
return [FBRequestConnection startWithGraphPath:graphPath
parameters:nil
HTTPMethod:nil
completionHandler:handler];
}
+ (FBRequestConnection*)startForPostWithGraphPath:(NSString*)graphPath
graphObject:(id<FBGraphObject>)graphObject
completionHandler:(FBRequestHandler)handler
{
FBRequest *request = [FBRequest requestForPostWithGraphPath:graphPath
graphObject:graphObject];
return [request startWithCompletionHandler:handler];
}
+ (FBRequestConnection*)startWithGraphPath:(NSString*)graphPath
parameters:(NSDictionary*)parameters
HTTPMethod:(NSString*)HTTPMethod
completionHandler:(FBRequestHandler)handler
{
FBRequest *request = [FBRequest requestWithGraphPath:graphPath
parameters:parameters
HTTPMethod:HTTPMethod];
return [request startWithCompletionHandler:handler];
}
// ----------------------------------------------------------------------------
// Private methods
- (void)startWithCacheIdentity:(NSString*)cacheIdentity
skipRoundtripIfCached:(BOOL)skipRoundtripIfCached
{
if ([self.requests count] == 1) {
FBRequestMetadata *firstMetadata = [self.requests objectAtIndex:0];
if ([firstMetadata.request delegate]) {
self.deprecatedRequest = firstMetadata.request;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
[self.deprecatedRequest setState:kFBRequestStateLoading];
#pragma GCC diagnostic pop
}
}
NSMutableURLRequest *request = nil;
NSData *cachedData = nil;
NSURL *cacheIdentityURL = nil;
if (cacheIdentity) {
// warning! this property has significant side-effects, and should be executed at the right moment
// depending on whether there may be batching or whether we are certain there is no batching
request = self.urlRequest;
// when we generalize this for consumers of FBRequest, then we will use a more
// normalized form for our identification scheme than this URL construction; given the only
// clients are the two pickers -- this scheme achieves stability via being a closed system,
// and provides a simple first step to the more general solution
cacheIdentityURL = [[[NSURL alloc] initWithScheme:@"FBRequestCache"
host:cacheIdentity
path:[NSString stringWithFormat:@"/%@", request.URL]]
autorelease];
if (skipRoundtripIfCached) {
cachedData = [[FBDataDiskCache sharedCache] dataForURL:cacheIdentityURL];
}
}
if (self.internalUrlRequest == nil && !cacheIdentity) {
// If we have all Graph API calls, see if we want to piggyback any internal calls onto
// the request to reduce round-trips. (The piggybacked calls may themselves be non-Graph
// API calls, but must be limited to API calls which are batchable. Not all are, which is
// why we won't piggyback on top of a REST API call.) Don't try this if the caller gave us
// an already-formed request object, since we don't know its structure.
BOOL safeForPiggyback = YES;
for (FBRequestMetadata *requestMetadata in self.requests) {
if (requestMetadata.request.restMethod) {
safeForPiggyback = NO;
break;
}
}
// If we wouldn't be able to compute a batch_app_id, don't piggyback on this
// request.
NSString *batchAppID = [self getBatchAppID:self.requests];
safeForPiggyback &= (batchAppID != nil) && (batchAppID.length > 0);
if (safeForPiggyback) {
[self addPiggybackRequests];
}
}
// warning! this property is side-effecting (and should probably be refactored at some point...)
// still, if we have made it this far and still don't have a request object, we need one now
if (!request) {
request = self.urlRequest;
}
NSAssert((self.state == kStateCreated) || (self.state == kStateSerialized),
@"Cannot call start again after calling start or cancel.");
self.state = kStateStarted;
_requestStartTime = [FBUtility currentTimeInMilliseconds];
if (!cachedData) {
FBURLConnectionHandler handler =
^(FBURLConnection *connection,
NSError *error,
NSURLResponse *response,
NSData *responseData) {
// cache this data if we have successful response and a cache identity to work with
if (cacheIdentityURL &&
[response isKindOfClass:[NSHTTPURLResponse class]] &&
((NSHTTPURLResponse*)response).statusCode == 200) {
[[FBDataDiskCache sharedCache] setData:responseData
forURL:cacheIdentityURL];
}
// complete on result from round-trip to server
[self completeWithResponse:response
data:responseData
orError:error];
};
id<FBRequestDelegate> deprecatedDelegate = [self.deprecatedRequest delegate];
if ([deprecatedDelegate respondsToSelector:@selector(requestLoading:)]) {
[deprecatedDelegate requestLoading:self.deprecatedRequest];
}
FBURLConnection *connection = [[FBURLConnection alloc] initWithRequest:request
skipRoundTripIfCached:NO
completionHandler:handler];
self.connection = connection;
[connection release];
} else {
_isResultFromCache = YES;
// complete on result from cache
[self completeWithResponse:nil
data:cachedData
orError:nil];
}
}
//
// Generates a NSURLRequest based on the contents of self.requests, and sets
// options on the request. Chooses between URL-based request for a single
// request and JSON-based request for batches.
//
- (NSMutableURLRequest *)requestWithBatch:(NSArray *)requests
timeout:(NSTimeInterval)timeout
{
FBRequestBody *body = [[FBRequestBody alloc] init];
FBLogger *bodyLogger = [[FBLogger alloc] initWithLoggingBehavior:_logger.loggingBehavior];
FBLogger *attachmentLogger = [[FBLogger alloc] initWithLoggingBehavior:_logger.loggingBehavior];
NSMutableURLRequest *request;
if (requests.count == 0) {
[[NSException exceptionWithName:FBInvalidOperationException
reason:@"FBRequestConnection: Must have at least one request or urlRequest not specified."
userInfo:nil]
raise];
}
if ([requests count] == 1) {
FBRequestMetadata *metadata = [requests objectAtIndex:0];
NSURL *url = [NSURL URLWithString:[self urlStringForSingleRequest:metadata.request forBatch:NO]];
request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:timeout];
// HTTP methods are case-sensitive; be helpful in case someone provided a mixed case one.
NSString *httpMethod = [metadata.request.HTTPMethod uppercaseString];
[request setHTTPMethod:httpMethod];
[self appendAttachments:metadata.request.parameters
toBody:body
addFormData:[httpMethod isEqualToString:@"POST"]
logger:attachmentLogger];
// if we have a post object, also roll that into the body
if (metadata.request.graphObject) {
[FBRequestConnection processGraphObject:metadata.request.graphObject
forPath:[url path]
withAction:^(NSString *key, id value) {
[body appendWithKey:key formValue:value logger:bodyLogger];
}];
}
} else {
// Find the session with an app ID and use that as the batch_app_id. If we can't
// find one, try to load it from the plist. As a last resort, pass 0.
NSString *batchAppID = [self getBatchAppID:requests];
if (!batchAppID || batchAppID.length == 0) {
// The Graph API batch method requires either an access token or batch_app_id.
// If we can't determine an App ID to use for the batch, we can't issue it.
[[NSException exceptionWithName:FBInvalidOperationException
reason:@"FBRequestConnection: At least one request in a"
" batch must have an open FBSession, or a default"
" app ID must be specified."
userInfo:nil]
raise];
}
[body appendWithKey:@"batch_app_id" formValue:batchAppID logger:bodyLogger];
NSMutableDictionary *attachments = [[NSMutableDictionary alloc] init];
[self appendJSONRequests:requests
toBody:body
andNameAttachments:attachments
logger:bodyLogger];
[self appendAttachments:attachments
toBody:body
addFormData:NO
logger:attachmentLogger];
[attachments release];
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:kGraphURL]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:timeout];
[request setHTTPMethod:@"POST"];
}
[request setHTTPBody:[body data]];
NSUInteger bodyLength = [[body data] length] / 1024;
[body release];
[request setValue:[FBRequestConnection userAgent] forHTTPHeaderField:@"User-Agent"];
[request setValue:[FBRequestBody mimeContentType] forHTTPHeaderField:@"Content-Type"];
[self logRequest:request bodyLength:bodyLength bodyLogger:bodyLogger attachmentLogger:attachmentLogger];
// Safely release now that everything's serialized into the logger.
[bodyLogger release];
[attachmentLogger release];
return request;
}
- (void)logRequest:(NSMutableURLRequest *)request
bodyLength:(int)bodyLength
bodyLogger:(FBLogger *)bodyLogger
attachmentLogger:(FBLogger *)attachmentLogger
{
if (_logger.isActive) {
[_logger appendFormat:@"Request <#%d>:\n", _logger.loggerSerialNumber];
[_logger appendKey:@"URL" value:[[request URL] absoluteString]];
[_logger appendKey:@"Method" value:[request HTTPMethod]];
[_logger appendKey:@"UserAgent" value:[request valueForHTTPHeaderField:@"User-Agent"]];
[_logger appendKey:@"MIME" value:[request valueForHTTPHeaderField:@"Content-Type"]];
if (bodyLength != 0) {
[_logger appendKey:@"Body Size" value:[NSString stringWithFormat:@"%d kB", bodyLength / 1024]];
}
if (bodyLogger != nil) {
[_logger appendKey:@"Body (w/o attachments)" value:bodyLogger.contents];
}
if (attachmentLogger != nil) {
[_logger appendKey:@"Attachments" value:attachmentLogger.contents];
}
[_logger appendString:@"\n"];
[_logger emitToNSLog];
}
}
//
// Generates a URL for a batch containing only a single request,
// and names all attachments that need to go in the body of the
// request.
//
// The URL contains all parameters that are not body attachments,
// including the session key if present.
//
// Attachments are named and referenced by name in the URL.
//
- (NSString *)urlStringForSingleRequest:(FBRequest *)request forBatch:(BOOL)forBatch
{
[request.parameters setValue:@"json" forKey:@"format"];
[request.parameters setValue:kSDK forKey:@"sdk"];
NSString *token = request.session.accessToken;
if (token) {
[request.parameters setValue:token forKey:kAccessTokenKey];
[self registerTokenToOmitFromLog:token];
}
NSString *baseURL;
if (request.restMethod) {
if (forBatch) {
baseURL = [kBatchRestMethodBaseURL stringByAppendingString:request.restMethod];
} else {
baseURL = [kRestBaseURL stringByAppendingString:request.restMethod];
}
} else {
if (forBatch) {
baseURL = request.graphPath;
} else {
baseURL = [kGraphBaseURL stringByAppendingString:request.graphPath];
}
}
NSString *url = [FBRequest serializeURL:baseURL
params:request.parameters
httpMethod:request.HTTPMethod];
return url;
}
// Find the first session with an app ID and use that as the batch_app_id. If we can't
// find one, return the default app ID (which may still be nil if not specified
// programmatically or via the plist).
- (NSString *)getBatchAppID:(NSArray*)requests
{
for (FBRequestMetadata *metadata in requests) {
if (metadata.request.session.appID.length > 0) {
return metadata.request.session.appID;
}
}
return [FBSession defaultAppID];
}
//
// Serializes all requests in the batch to JSON and appends the result to
// body. Also names all attachments that need to go as separate blocks in
// the body of the request.
//
// All the requests are serialized into JSON, with any binary attachments
// named and referenced by name in the JSON.
//
- (void)appendJSONRequests:(NSArray *)requests
toBody:(FBRequestBody *)body
andNameAttachments:(NSMutableDictionary *)attachments
logger:(FBLogger *)logger
{
NSMutableArray *batch = [[NSMutableArray alloc] init];
for (FBRequestMetadata *metadata in requests) {
[self addRequest:metadata
toBatch:batch
attachments:attachments];
}
FBSBJSON *writer = [[FBSBJSON alloc] init];
NSString *jsonBatch = [writer stringWithObject:batch];
[writer release];
[batch release];
[body appendWithKey:kBatchKey formValue:jsonBatch logger:logger];
}
//
// Adds request data to a batch in a format expected by the JsonWriter.
// Binary attachments are referenced by name in JSON and added to the
// attachments dictionary.
//
- (void)addRequest:(FBRequestMetadata *)metadata
toBatch:(NSMutableArray *)batch
attachments:(NSDictionary *)attachments
{
NSMutableDictionary *requestElement = [[[NSMutableDictionary alloc] init] autorelease];
if (metadata.batchEntryName) {
[requestElement setObject:metadata.batchEntryName forKey:@"name"];
}
NSString *token = metadata.request.session.accessToken;
if (token) {
[metadata.request.parameters setObject:token forKey:kAccessTokenKey];
[self registerTokenToOmitFromLog:token];
}
NSString *urlString = [self urlStringForSingleRequest:metadata.request forBatch:YES];
[requestElement setObject:urlString forKey:kBatchRelativeURLKey];
[requestElement setObject:metadata.request.HTTPMethod forKey:kBatchMethodKey];
NSMutableString *attachmentNames = [NSMutableString string];
for (id key in [metadata.request.parameters keyEnumerator]) {
NSObject *value = [metadata.request.parameters objectForKey:key];
if ([self isAttachment:value]) {
NSString *name = [NSString stringWithFormat:@"%@%d",
kBatchFileNamePrefix,
[attachments count]];
if ([attachmentNames length]) {
[attachmentNames appendString:@","];
}
[attachmentNames appendString:name];
[attachments setValue:value forKey:name];
}
}
// if we have a post object, also roll that into the body
if (metadata.request.graphObject) {
NSMutableString *bodyValue = [[[NSMutableString alloc] init] autorelease];
__block NSString *delimiter = @"";
[FBRequestConnection
processGraphObject:metadata.request.graphObject
forPath:urlString
withAction:^(NSString *key, id value) {
// escape the value
value = [FBUtility stringByURLEncodingString:[value description]];
[bodyValue appendFormat:@"%@%@=%@",
delimiter,
key,
value];
delimiter = @"&";
}];
[requestElement setObject:bodyValue forKey:@"body"];
}
if ([attachmentNames length]) {
[requestElement setObject:attachmentNames forKey:kBatchAttachmentKey];
}
[batch addObject:requestElement];
}
- (BOOL)isAttachment:(id)item
{
return
[item isKindOfClass:[UIImage class]] ||
[item isKindOfClass:[NSData class]];
}
- (void)appendAttachments:(NSDictionary *)attachments
toBody:(FBRequestBody *)body
addFormData:(BOOL)addFormData
logger:(FBLogger *)logger
{
// key is name for both, first case is string which we can print, second pass grabs object
if (addFormData) {
for (NSString *key in [attachments keyEnumerator]) {
NSObject *value = [attachments objectForKey:key];
if ([value isKindOfClass:[NSString class]]) {
[body appendWithKey:key formValue:(NSString *)value logger:logger];
}
}
}
for (NSString *key in [attachments keyEnumerator]) {
NSObject *value = [attachments objectForKey:key];
if ([value isKindOfClass:[UIImage class]]) {
[body appendWithKey:key imageValue:(UIImage *)value logger:logger];
} else if ([value isKindOfClass:[NSData class]]) {
[body appendWithKey:key dataValue:(NSData *)value logger:logger];
}
}
}
#pragma mark Graph Object serialization
+ (void)processGraphObjectPropertyKey:(NSString*)key
value:(id)value
action:(KeyValueActionHandler)action
passByValue:(BOOL)passByValue {
if ([value conformsToProtocol:@protocol(FBGraphObject)]) {
NSDictionary<FBGraphObject> *refObject = (NSDictionary<FBGraphObject>*)value;
if (passByValue) {
// We need to pass all properties of this object in key[propertyName] format.
for (NSString *propertyName in refObject) {
NSString *subKey = [NSString stringWithFormat:@"%@[%@]", key, propertyName];
id subValue = [refObject objectForKey:propertyName];
// Note that passByValue is not inherited by subkeys.
[self processGraphObjectPropertyKey:subKey value:subValue action:action passByValue:NO];
}
} else {
// Normal case is passing objects by reference, so just pass the ID or URL, if any.
NSString *subValue;
if ((subValue = [refObject objectForKey:@"id"])) { // fbid
if ([subValue isKindOfClass:[NSDecimalNumber class]]) {
subValue = [(NSDecimalNumber*)subValue stringValue];
}
action(key, subValue);
} else if ((subValue = [refObject objectForKey:@"url"])) { // canonical url (external)
action(key, subValue);
}
}
} else if ([value isKindOfClass:[NSString class]] ||
[value isKindOfClass:[NSNumber class]]) {
// Just serialize these.
action(key, value);
} else if ([value isKindOfClass:[NSArray class]]) {
// Arrays are serialized as multiple elements with keys of the
// form key[0], key[1], etc.
NSArray *array = (NSArray*)value;
int count = array.count;
for (int i = 0; i < count; ++i) {
NSString *subKey = [NSString stringWithFormat:@"%@[%d]", key, i];
id subValue = [array objectAtIndex:i];
[self processGraphObjectPropertyKey:subKey value:subValue action:action passByValue:passByValue];
}
}
}
+ (void)processGraphObject:(id<FBGraphObject>)object forPath:(NSString*)path withAction:(KeyValueActionHandler)action {
BOOL isOGAction = NO;
if ([path hasPrefix:@"me/"] ||
[path hasPrefix:@"/me/"]) {
// In general, graph objects are passed by reference (ID/URL). But if this is an OG Action,
// we need to pass the entire values of the contents of the 'image' property, as they
// contain important metadata beyond just a URL. We don't have a 100% foolproof way of knowing
// if we are posting an OG Action, given that batched requests can have parameter substitution,
// but passing the OG Action type as a substituted parameter is unlikely.
// It looks like an OG Action if it's posted to me/namespace:action[?other=stuff].
NSUInteger colonLocation = [path rangeOfString:@":"].location;
NSUInteger questionMarkLocation = [path rangeOfString:@"?"].location;
isOGAction = (colonLocation != NSNotFound && colonLocation > 3) &&
(questionMarkLocation == NSNotFound || colonLocation < questionMarkLocation);
}
for (NSString *key in [object keyEnumerator]) {
NSObject *value = [object objectForKey:key];
BOOL passByValue = isOGAction && [key isEqualToString:@"image"];
[self processGraphObjectPropertyKey:key value:value action:action passByValue:passByValue];
}
}
#pragma mark -
- (void)completeWithResponse:(NSURLResponse *)response
data:(NSData *)data
orError:(NSError *)error
{
NSAssert(self.state == kStateStarted,
@"Unexpected state %d in completeWithResponse",
self.state);
self.state = kStateCompleted;
int statusCode;
if (response) {
NSAssert([response isKindOfClass:[NSHTTPURLResponse class]],
@"Expected NSHTTPURLResponse, got %@",
response);
self.urlResponse = (NSHTTPURLResponse *)response;
statusCode = self.urlResponse.statusCode;
if (!error && [response.MIMEType hasPrefix:@"image"]) {
error = [self errorWithCode:FBErrorNonTextMimeTypeReturned
statusCode:0
parsedJSONResponse:nil
innerError:nil
message:@"Response is a non-text MIME type; endpoints that return images and other "
@"binary data should be fetched using NSURLRequest and NSURLConnection"];
}
} else {
// the cached case is always successful, from an http perspective
statusCode = 200;
}
NSArray *results = nil;
if (!error) {
results = [self parseJSONResponse:data
error:&error
statusCode:statusCode];
}
// the cached case has data but no response,
// in which case we skip connection-related errors
if (response || !data) {
error = [self checkConnectionError:error
statusCode:statusCode
parsedJSONResponse:results];
}
if (!error) {
if ([self.requests count] != [results count]) {
NSLog(@"Expected %d results, got %d", [self.requests count], [results count]);
error = [self errorWithCode:FBErrorProtocolMismatch
statusCode:statusCode
parsedJSONResponse:results
innerError:nil
message:nil];
}
}
if (!error) {
[_logger appendFormat:@"Response <#%d>\nDuration: %lu msec\nSize: %d kB\nResponse Body:\n%@\n\n",
[_logger loggerSerialNumber],
[FBUtility currentTimeInMilliseconds] - _requestStartTime,
[data length],
results];
} else {
[_logger appendFormat:@"Response <#%d> <Error>:\n%@\n\n",
[_logger loggerSerialNumber],
[error localizedDescription]];
}
[_logger emitToNSLog];
if (self.deprecatedRequest) {
[self completeDeprecatedWithData:data results:results orError:error];
} else {
[self completeWithResults:results orError:error];
}
self.connection = nil;
self.urlResponse = (NSHTTPURLResponse *)response;
}
//
// If there is one request, the JSON is the response.
// If there are multiple requests, the JSON has an array of dictionaries whose
// body property is the response.
// [{ "code":200,
// "body":"JSON-response-as-a-string" },
// { "code":200,
// "body":"JSON-response-as-a-string" }]
//
// In both cases, this function returns an NSArray containing the results.
// The NSArray looks just like the multiple request case except the body
// value is converted from a string to parsed JSON.