This repository was archived by the owner on Sep 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathGDataServiceBase.m
2293 lines (1864 loc) · 76.9 KB
/
GDataServiceBase.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 (c) 2007 Google Inc.
*
* 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.
*/
//
// GDataServiceBase.m
//
#import <TargetConditionals.h>
#if TARGET_OS_MAC
#include <sys/utsname.h>
#endif
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#endif
#define GDATASERVICEBASE_DEFINE_GLOBALS 1
#import "GDataServiceBase.h"
#import "GDataServerError.h"
#import "GDataFramework.h"
static NSString *const kXMLErrorContentType = @"application/vnd.google.gdata.error+xml";
static NSString* const kFetcherDelegateKey = @"_delegate";
static NSString* const kFetcherObjectClassKey = @"_objectClass";
static NSString* const kFetcherFinishedSelectorKey = @"_finishedSelector";
static NSString* const kFetcherCompletionHandlerKey = @"_completionHandler";
static NSString* const kFetcherTicketKey = @"_ticket";
static NSString* const kFetcherStreamDataKey = @"_streamData";
static NSString* const kFetcherParsedObjectKey = @"_parsedObject";
static NSString* const kFetcherParseErrorKey = @"_parseError";
static NSString* const kFetcherCallbackThreadKey = @"_callbackThread";
static NSString* const kFetcherCallbackRunLoopModesKey = @"_runLoopModes";
NSString* const kFetcherRetryInvocationKey = @"_retryInvocation";
static const NSUInteger kMaxNumberOfNextLinksFollowed = 25;
// we'll enforce 50K chunks minimum just to avoid the server getting hit
// with too many small upload chunks
static const NSUInteger kMinimumUploadChunkSize = 50000;
// XorPlainMutableData is a simple way to keep passwords held in heap objects
// from being visible as plain-text
static void XorPlainMutableData(NSMutableData *mutableData) {
// this helps avoid storing passwords on the heap in plaintext
const unsigned char theXORValue = 0x95; // 0x95 = 0xb10010101
unsigned char *dataPtr = [mutableData mutableBytes];
NSUInteger length = [mutableData length];
for (NSUInteger idx = 0; idx < length; idx++) {
dataPtr[idx] ^= theXORValue;
}
}
// category to provide opaque access to tickets stored in fetcher properties
@implementation GTMBridgeFetcher (GDataServiceTicketAdditions)
- (id)GDataTicket {
return [self propertyForKey:kFetcherTicketKey];
}
@end
@interface GDataUploadFetcherClass : GTMBridgeFetcher
// If GDataUploadFetcher is available, it can be used for chunked uploads
//
// We locally declare some methods of GDataUploadFetcher so we do not need to import the header,
// as some projects may not have it available. The declared methods vary depending on the value of
// GTM_USE_SESSION_FETCHER, since one is based on GTMSessionUploadFetcher and the other on
// GTMHTTPUploadFetcher.
#if GTM_USE_SESSION_FETCHER
+ (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request
uploadMIMEType:(NSString *)uploadMIMEType
chunkSize:(int64_t)chunkSize
fetcherService:(GTMSessionFetcherService *)fetcherServiceOrNil;
+ (instancetype)uploadFetcherWithLocation:(NSURL *)uploadLocationURL
uploadMIMEType:(NSString *)uploadMIMEType
chunkSize:(int64_t)chunkSize
fetcherService:(GTMSessionFetcherService *)fetcherServiceOrNil;
@property(strong) NSURL *uploadLocationURL;
@property(strong) NSData *uploadData;
@property(strong) NSURL *uploadFileURL;
@property(strong) NSFileHandle *uploadFileHandle;
#else
+ (GTMHTTPUploadFetcher *)uploadFetcherWithRequest:(NSURLRequest *)request
uploadData:(NSData *)data
uploadMIMEType:(NSString *)uploadMIMEType
chunkSize:(NSUInteger)chunkSize
fetcherService:(GTMHTTPFetcherService *)fetcherService;
+ (GTMHTTPUploadFetcher *)uploadFetcherWithRequest:(NSURLRequest *)request
uploadFileHandle:(NSFileHandle *)uploadFileHandle
uploadMIMEType:(NSString *)uploadMIMEType
chunkSize:(NSUInteger)chunkSize
fetcherService:(GTMHTTPFetcherService *)fetcherService;
+ (GTMHTTPUploadFetcher *)uploadFetcherWithLocation:(NSURL *)locationURL
uploadFileHandle:(NSFileHandle *)uploadFileHandle
uploadMIMEType:(NSString *)uploadMIMEType
chunkSize:(NSUInteger)chunkSize
fetcherService:(GTMHTTPFetcherService *)fetcherService;
#endif // GTM_USE_SESSION_FETCHER
- (void)pauseFetching;
- (void)resumeFetching;
- (BOOL)isPaused;
@end
@interface GDataEntryBase (PrivateMethods)
- (NSDictionary *)contentHeaders;
@end
@interface GDataServiceBase (PrivateMethods)
- (BOOL)fetchNextFeedWithURL:(NSURL *)nextFeedURL
delegate:(id)delegate
didFinishedSelector:(SEL)finishedSelector
completionHandler:(GDataServiceCompletionHandler)completionHandler
ticket:(GDataServiceTicketBase *)ticket;
- (NSDictionary *)userInfoForErrorResponseData:(NSData *)data
contentType:(NSString *)contentType
previousUserInfo:(NSDictionary *)previousUserInfo;
- (void)objectFetcher:(GTMBridgeFetcher *)fetcher
finishedWithData:(NSData *)data
error:(NSError *)error;
- (void)objectFetcher:(GTMBridgeFetcher *)fetcher
failedWithData:(NSData *)data
error:(NSError *)error;
- (BOOL)objectFetcher:(GTMBridgeFetcher *)fetcher
willRetry:(BOOL)willRetry
forError:(NSError *)error;
- (void)objectFetcher:(GTMBridgeFetcher *)fetcher
didSendBytes:(NSInteger)bytesSent
totalBytesSent:(NSInteger)totalBytesSent
totalBytesExpectedToSend:(NSInteger)totalBytesExpected;
- (void)parseObjectFromDataOfFetcher:(GTMBridgeFetcher *)fetcher;
- (void)handleParsedObjectForFetcher:(GTMBridgeFetcher *)fetcher;
@end
@implementation GDataServiceBase
+ (Class)ticketClass {
return [GDataServiceTicketBase class];
}
- (id)init {
self = [super init];
if (self) {
#if GDATA_IPHONE || (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5)
operationQueue_ = [[NSOperationQueue alloc] init];
#elif !GDATA_SKIP_PARSE_THREADING
// Avoid NSOperationQueue prior to 10.5.6, per
// http://www.mikeash.com/?page=pyblog/use-nsoperationqueue.html
SInt32 bcdSystemVersion = 0;
(void) Gestalt(gestaltSystemVersion, &bcdSystemVersion);
if (bcdSystemVersion >= 0x1057) {
operationQueue_ = [[NSOperationQueue alloc] init];
}
#else
// operationQueue_ defaults to nil, so parsing will be done immediately
// on the current thread
#endif
fetcherService_ = [[GTMBridgeFetcherService alloc] init];
#if !GTM_USE_SESSION_FETCHER
[fetcherService_ setShouldRememberETags:YES];
#endif
cookieStorageMethod_ = -1;
NSUInteger chunkSize = [[self class] defaultServiceUploadChunkSize];
[self setServiceUploadChunkSize:chunkSize];
}
return self;
}
- (void)dealloc {
[operationQueue_ release];
[serviceVersion_ release];
[userAgent_ release];
[fetcherService_ release];
[username_ release];
[password_ release];
[serviceUserData_ release];
[serviceProperties_ release];
[serviceSurrogates_ release];
#if NS_BLOCKS_AVAILABLE
[serviceUploadProgressBlock_ release];
#endif
[super dealloc];
}
+ (NSString *)systemVersionString {
NSString *str = GTMBridgeSystemVersionString();
return str;
}
- (NSString *)requestUserAgent {
NSString *userAgent = [self userAgent];
if ([userAgent length] == 0 || [userAgent hasPrefix:@"MyCompany-"]) {
// the service instance is missing an explicit user-agent; use the bundle ID
// or process name
userAgent = [[self class] defaultApplicationIdentifier];
}
NSString *requestUserAgent = userAgent;
// if the user agent already specifies the library version, we'll
// use it verbatim in the request
NSString *libraryString = @"GData-ObjectiveC";
NSRange libRange = [userAgent rangeOfString:libraryString
options:NSCaseInsensitiveSearch];
if (libRange.location == NSNotFound) {
// the user agent doesn't specify the client library, so append that
// information, and the system version
NSString *libVersionString = GDataFrameworkVersionString();
NSString *systemString = [[self class] systemVersionString];
// Google servers look for gzip in the user agent before sending gzip-
// encoded responses. See Service.java
requestUserAgent = [NSString stringWithFormat:@"%@ %@/%@ %@ (gzip)",
userAgent, libraryString, libVersionString, systemString];
}
return requestUserAgent;
}
- (NSMutableURLRequest *)requestForURL:(NSURL *)url
ETag:(NSString *)etag
httpMethod:(NSString *)httpMethod
ticket:(GDataServiceTicketBase *)ticket {
// subclasses may add headers to this
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] autorelease];
NSString *requestUserAgent = [self requestUserAgent];
[request setValue:requestUserAgent forHTTPHeaderField:@"User-Agent"];
NSString *serviceVersion = [self serviceVersion];
if ([serviceVersion length] > 0) {
// only add a version header if the URL lacks a v= version parameter
NSString *queryString = [url query];
if (queryString == nil
|| ([queryString rangeOfString:@"&v="].location == NSNotFound
&& ![queryString hasPrefix:@"v="])) {
[request setValue:serviceVersion forHTTPHeaderField:@"GData-Version"];
}
}
if ([httpMethod length] > 0) {
[request setHTTPMethod:httpMethod];
}
if ([etag length] > 0) {
// it's rather unexpected for an etagged object to be provided for a GET,
// but we'll check for an etag anyway, similar to HttpGDataRequest.java,
// and if present use it to request only an unchanged resource
BOOL isDoingHTTPGet = (httpMethod == nil
|| [httpMethod caseInsensitiveCompare:@"GET"] == NSOrderedSame);
if (isDoingHTTPGet) {
// set the etag header, even if weak, indicating we don't want
// another copy of the resource if it's the same as the object
[request setValue:etag forHTTPHeaderField:@"If-None-Match"];
} else {
// if we're doing PUT or DELETE, set the etag header indicating
// we only want to update the resource if our copy matches the current
// one (unless the etag is weak and so shouldn't be a constraint at all)
BOOL isWeakETag = [etag hasPrefix:@"W/"];
BOOL isModifying =
[httpMethod caseInsensitiveCompare:@"PUT"] == NSOrderedSame
|| [httpMethod caseInsensitiveCompare:@"DELETE"] == NSOrderedSame
|| [httpMethod caseInsensitiveCompare:@"PATCH"] == NSOrderedSame;
if (isModifying && !isWeakETag) {
[request setValue:etag forHTTPHeaderField:@"If-Match"];
}
}
}
return request;
}
- (NSMutableURLRequest *)requestForURL:(NSURL *)url
ETag:(NSString *)etag
httpMethod:(NSString *)httpMethod {
// this public entry point authenticates from the service object but
// not from the auth token in the ticket
return [self requestForURL:url ETag:etag httpMethod:httpMethod ticket:nil];
}
// objectRequestForURL returns an NSMutableURLRequest for a GData object as XML
//
// the object is the object being sent to the server, or nil;
// the http method may be nil for get, or POST, PUT, DELETE
- (NSMutableURLRequest *)objectRequestForURL:(NSURL *)url
object:(GDataObject *)object
ETag:(NSString *)etag
httpMethod:(NSString *)httpMethod
ticket:(GDataServiceTicketBase *)ticket {
NSString *contentType = @"application/atom+xml; charset=utf-8";
if (object) {
// if the object being sent has an etag, add it to the request header to
// avoid retrieving a duplicate or to avoid writing over an updated
// version of the resource on the server
//
// Typically, delete requests will provide an explicit ETag parameter, and
// other requests will have the ETag carried inside the object being updated
if (etag == nil) {
SEL selEtag = @selector(ETag);
if ([object respondsToSelector:selEtag]) {
etag = [object performSelector:selEtag];
}
}
if (httpMethod != nil
&& [httpMethod caseInsensitiveCompare:@"PATCH"] == NSOrderedSame) {
// PATCH isn't part of Atom
contentType = @"application/xml; charset=utf-8";
}
}
NSMutableURLRequest *request = [self requestForURL:url
ETag:etag
httpMethod:httpMethod
ticket:ticket];
[request setValue:@"application/atom+xml, text/xml" forHTTPHeaderField:@"Accept"];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
[request setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
return request;
}
#pragma mark -
- (GDataServiceTicketBase *)fetchObjectWithURL:(NSURL *)feedURL
objectClass:(Class)objectClass
objectToPost:(GDataObject *)objectToPost
ETag:(NSString *)etag
httpMethod:(NSString *)httpMethod
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector
completionHandler:(id)completionHandler // GDataServiceCompletionHandler
retryInvocationValue:(NSValue *)retryInvocationValue
ticket:(GDataServiceTicketBase *)ticket {
GTMBridgeAssertValidSelector(delegate, finishedSelector, @encode(GDataServiceTicketBase *), @encode(GDataObject *), @encode(NSError *), 0);
// The completionHandler argument is declared as an id, not as a block
// pointer, so this can be built with the 10.6 SDK and still run on 10.5.
// If the argument were declared as a block pointer, the invocation for
// fetchObjectWithURL: created in GDataServiceGoogle would cause an exception
// since 10.5's NSInvocation cannot deal with encoding of block pointers.
NSURL *uploadLocationURL = [objectToPost uploadLocationURL];
// if no URL was supplied, and we're not resuming an upload, treat this as
// if the fetch failed (below) and immediately return a nil ticket, skipping
// the callbacks
//
// this might be considered normal (say, updating a read-only entry
// that lacks an edit link) though higher-level calls may assert or
// returns errors depending on the specific usage
if (feedURL == nil && uploadLocationURL == nil) {
return nil;
}
// we need to create a ticket unless one was created earlier (like during
// authentication)
if (!ticket) {
ticket = [[[self class] ticketClass] ticketForService:self];
}
NSMutableURLRequest *request = nil;
if (feedURL) {
request = [self objectRequestForURL:feedURL
object:objectToPost
ETag:etag
httpMethod:httpMethod
ticket:ticket];
}
GTMBridgeAssertValidSelector(delegate, [ticket uploadProgressSelector],
@encode(GDataServiceTicketBase *), @encode(unsigned long long),
@encode(unsigned long long), 0);
GTMBridgeAssertValidSelector(delegate, [ticket retrySelector],
@encode(GDataServiceTicketBase *), @encode(BOOL), @encode(NSError *), 0);
//
// package the object's XML and any upload data
//
NSInputStream *streamToPost = nil;
NSData *dataToPost = nil;
SEL sentDataSel = NULL;
NSData *uploadData = nil;
NSFileHandle *uploadFileHandle = nil;
BOOL shouldUploadDataChunked = ([self serviceUploadChunkSize] > 0);
BOOL isUploadingDataChunked = NO;
NSMutableDictionary *uploadProperties = nil;
if (objectToPost) {
NSData *xmlData = nil;
[ticket setPostedObject:objectToPost];
// An upload object may provide a custom input stream, such as for
// multi-part MIME or media uploads.
NSInputStream *contentInputStream = nil;
unsigned long long contentLength = 0;
NSDictionary *contentHeaders = nil;
uploadProperties = [NSMutableDictionary dictionary];
BOOL doesSupportSentData = YES;
#if !GTM_USE_SESSION_FETCHER
doesSupportSentData = [GTMBridgeFetcher doesSupportSentDataCallback];
#endif
uploadData = [objectToPost uploadData];
uploadFileHandle = [objectToPost uploadFileHandle];
isUploadingDataChunked = ((uploadData != nil || uploadFileHandle != nil)
&& shouldUploadDataChunked);
BOOL shouldUploadDataOnly = ([objectToPost shouldUploadDataOnly]
|| uploadLocationURL != nil);
BOOL shouldReportUploadProgress;
#if NS_BLOCKS_AVAILABLE
shouldReportUploadProgress = ([ticket uploadProgressSelector] != NULL
|| [ticket uploadProgressHandler] != NULL);
#else
shouldReportUploadProgress = ([ticket uploadProgressSelector] != NULL);
#endif
if ((!isUploadingDataChunked) &&
[objectToPost generateContentInputStream:&contentInputStream
length:&contentLength
headers:&contentHeaders]) {
// now we have a stream containing the XML and the upload data
} else if (isUploadingDataChunked && shouldUploadDataOnly) {
// no XML is needed since we're uploading data only, and there's no upload
// data for the first fetch because the data will be sent chunked later,
// so now we'll have an empty body with appropriate headers
contentHeaders = [objectToPost performSelector:@selector(contentHeaders)];
contentLength = 0;
} else {
// we're sending either just XML, or XML now with chunked upload data
// later
xmlData = [[objectToPost XMLDocument] XMLData];
contentLength = [xmlData length];
if (!shouldReportUploadProgress
|| doesSupportSentData
|| isUploadingDataChunked) {
// there is no progress selector, or the fetcher can call us back on
// sent data, or we're uploading chunked; we can post plain NSData,
// which is simpler because it survives http redirects
dataToPost = xmlData;
} else {
// there is a progress selector and NSURLConnection won't call us back,
// so we need to be posting a stream
//
// we'll make a default input stream from the XML data
contentInputStream = [NSInputStream inputStreamWithData:xmlData];
// NSInputStream fails to retain or copy its data in 10.4, so we will
// retain it in the callback dictionary. We won't use this property in
// the callbacks at all, but retaining it will ensure it's still around
// until the upload completes.
//
// If it weren't for this bug in NSInputStream, we could just have
// GDataObject's -contentInputStream method create the input stream for
// us, so this service class wouldn't ever need to have the plain XML.
[uploadProperties setObject:xmlData forKey:kFetcherStreamDataKey];
}
if ([objectToPost respondsToSelector:@selector(uploadSlug)]) {
NSString *slug = [objectToPost performSelector:@selector(uploadSlug)];
if ([slug length] > 0) {
[request setValue:slug forHTTPHeaderField:@"Slug"];
}
}
}
if (contentHeaders) {
// add the content-specific headers, if any
for (NSString *key in contentHeaders) {
NSString *value = [contentHeaders objectForKey:key];
[request setValue:value forHTTPHeaderField:key];
}
}
streamToPost = contentInputStream;
NSNumber* num = [NSNumber numberWithUnsignedLongLong:contentLength];
[request setValue:[num stringValue] forHTTPHeaderField:@"Content-Length"];
if (shouldReportUploadProgress) {
if (doesSupportSentData || isUploadingDataChunked) {
// there is sentData callback support in NSURLConnection,
// or we're using an upload fetcher which can always call us
// back
sentDataSel = @selector(objectFetcher:didSendBytes:totalBytesSent:totalBytesExpectedToSend:);
}
}
}
//
// now that we have all the request header info ready,
// create and set up the fetcher for this request
//
GTMBridgeFetcher* fetcher = nil;
if (isUploadingDataChunked) {
GDataUploadFetcherClass *uploadFetcher;
// hang on to the user's requested chunk size, and ensure it's not tiny
NSUInteger uploadChunkSize = [self serviceUploadChunkSize];
if (uploadChunkSize < kMinimumUploadChunkSize) {
uploadChunkSize = kMinimumUploadChunkSize;
}
#ifdef GDATA_TARGET_NAMESPACE
// prepend the class name prefix
Class uploadClass = NSClassFromString(@GDATA_TARGET_NAMESPACE_STRING
@"_" GDataUploadFetcherClassStr);
#else
Class uploadClass = NSClassFromString(GDataUploadFetcherClassStr);
#endif
GDATA_ASSERT(uploadClass != nil, GDataUploadFetcherClassStr @" needed");
NSString *uploadMIMEType = [objectToPost uploadMIMEType];
#if GTM_USE_SESSION_FETCHER
if (uploadLocationURL) {
// Resuming with the session fetcher and a file handle.
GDATA_DEBUG_ASSERT(uploadFileHandle != nil, @"Resume requires a file handle");
uploadFetcher = [uploadClass uploadFetcherWithLocation:uploadLocationURL
uploadMIMEType:uploadMIMEType
chunkSize:(int64_t)uploadChunkSize
fetcherService:fetcherService_];
uploadFetcher.uploadFileHandle = uploadFileHandle;
} else {
uploadFetcher = [uploadClass uploadFetcherWithRequest:request
uploadMIMEType:uploadMIMEType
chunkSize:(int64_t)uploadChunkSize
fetcherService:fetcherService_];
if (uploadData) {
uploadFetcher.uploadData = uploadData;
} else if (uploadFileHandle) {
uploadFetcher.uploadFileHandle = uploadFileHandle;
}
}
#else // !GTM_USE_SESSION_FETCHER
if (uploadData) {
uploadFetcher = [uploadClass uploadFetcherWithRequest:request
uploadData:uploadData
uploadMIMEType:uploadMIMEType
chunkSize:uploadChunkSize
fetcherService:fetcherService_];
} else if (uploadLocationURL) {
uploadFetcher = [uploadClass uploadFetcherWithLocation:uploadLocationURL
uploadFileHandle:uploadFileHandle
uploadMIMEType:uploadMIMEType
chunkSize:uploadChunkSize
fetcherService:fetcherService_];
} else {
uploadFetcher = [uploadClass uploadFetcherWithRequest:request
uploadFileHandle:uploadFileHandle
uploadMIMEType:uploadMIMEType
chunkSize:uploadChunkSize
fetcherService:fetcherService_];
}
#endif
fetcher = uploadFetcher;
} else {
fetcher = [fetcherService_ fetcherWithRequest:request];
}
// allow the user to specify static app-wide cookies for fetching
NSInteger cookieStorageMethod = [self cookieStorageMethod];
if (cookieStorageMethod >= 0) {
[fetcher setCookieStorageMethod:cookieStorageMethod];
}
// copy the ticket's retry settings into the fetcher
[fetcher setRetryEnabled:[ticket isRetryEnabled]];
[fetcher setMaxRetryInterval:[ticket maxRetryInterval]];
if ([ticket retrySelector]) {
#if GTM_USE_SESSION_FETCHER
__block GTMBridgeFetcher *fetcherRef = fetcher;
fetcher.retryBlock = ^(BOOL suggestedWillRetry, NSError *error,
GTMSessionFetcherRetryResponse response) {
BOOL shouldRetry = [self objectFetcher:fetcherRef
willRetry:suggestedWillRetry
forError:error];
response(shouldRetry);
};
#else
[fetcher setRetrySelector:@selector(objectFetcher:willRetry:forError:)];
#endif
}
// remember the object fetcher in the ticket
[ticket setObjectFetcher:fetcher];
[ticket setCurrentFetcher:fetcher];
// add parameters used by the callbacks
[fetcher setProperty:objectClass forKey:kFetcherObjectClassKey];
[fetcher setProperty:delegate forKey:kFetcherDelegateKey];
[fetcher setProperty:NSStringFromSelector(finishedSelector)
forKey:kFetcherFinishedSelectorKey];
[fetcher setProperty:ticket
forKey:kFetcherTicketKey];
#if NS_BLOCKS_AVAILABLE
// copy the completion handler block to the heap; this does nothing if the
// block is already on the heap
completionHandler = [[completionHandler copy] autorelease];
[fetcher setProperty:completionHandler
forKey:kFetcherCompletionHandlerKey];
#endif
// we want to add the invocation itself, not the value wrapper of it,
// to ensure the invocation is retained until the callback completes
NSInvocation *retryInvocation = [retryInvocationValue nonretainedObjectValue];
[fetcher setProperty:retryInvocation
forKey:kFetcherRetryInvocationKey];
// set the upload data
GDATA_DEBUG_ASSERT(dataToPost == nil || streamToPost == nil,
@"upload conflict");
if (dataToPost) {
[fetcher setBodyData:dataToPost];
} else if (streamToPost) {
#if GTM_USE_SESSION_FETCHER
[fetcher setBodyStreamProvider:^(GTMSessionFetcherBodyStreamProviderResponse response) {
response(streamToPost);
}];
#else
[fetcher setPostStream:streamToPost];
#endif
}
if (sentDataSel) {
#if GTM_USE_SESSION_FETCHER
fetcher.sendProgressBlock = ^(int64_t bytesSent,
int64_t totalBytesSent,
int64_t totalBytesExpectedToSend) {
[self objectFetcher:fetcher
didSendBytes:(NSInteger)bytesSent
totalBytesSent:(NSInteger)totalBytesSent
totalBytesExpectedToSend:(NSInteger)totalBytesExpectedToSend];
};
#else
[fetcher setSentDataSelector:sentDataSel];
#endif
}
[fetcher addPropertiesFromDictionary:uploadProperties];
// attach OAuth authorization object, if any
//
// the fetcher already has this authorizer from the fetcher service, but this
// lets the client remove the authorizer from the ticket to make an
// unauthorized request
[fetcher setAuthorizer:[ticket authorizer]];
// add username/password, if any
[self addAuthenticationToFetcher:fetcher];
if (finishedSelector) {
[fetcher setComment:NSStringFromSelector(finishedSelector)];
}
// failed fetches call the failure selector, which will delete the ticket
BOOL didFetch = YES;
#if GTM_USE_SESSION_FETCHER
[fetcher beginFetchWithDelegate:self
didFinishSelector:@selector(objectFetcher:finishedWithData:error:)];
#else
didFetch = [fetcher beginFetchWithDelegate:self
didFinishSelector:@selector(objectFetcher:finishedWithData:error:)];
#endif
// If something weird happens and the networking callbacks have been called
// already synchronously, we don't want to return the ticket since the caller
// will never know when to stop retaining it, so we'll make sure the
// success/failure callbacks have not yet been called by checking the
// ticket
if (!didFetch || [ticket hasCalledCallback]) {
[fetcher setProperties:nil];
[ticket setCurrentFetcher:nil];
return nil;
}
return ticket;
}
- (void)invokeProgressCallbackForTicket:(GDataServiceTicketBase *)ticket
deliveredBytes:(unsigned long long)numReadSoFar
totalBytes:(unsigned long long)total {
SEL progressSelector = [ticket uploadProgressSelector];
if (progressSelector) {
GTMBridgeFetcher *fetcher = [ticket objectFetcher];
id delegate = [fetcher propertyForKey:kFetcherDelegateKey];
NSMethodSignature *signature = [delegate methodSignatureForSelector:progressSelector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:progressSelector];
[invocation setTarget:delegate];
[invocation setArgument:&ticket atIndex:2];
[invocation setArgument:&numReadSoFar atIndex:3];
[invocation setArgument:&total atIndex:4];
[invocation invoke];
}
#if NS_BLOCKS_AVAILABLE
GDataServiceUploadProgressHandler block = [ticket uploadProgressHandler];
if (block) {
block(ticket, numReadSoFar, total);
}
#endif
}
// sentData callback from fetcher
- (void)objectFetcher:(GTMBridgeFetcher *)fetcher
didSendBytes:(NSInteger)bytesSent
totalBytesSent:(NSInteger)totalBytesSent
totalBytesExpectedToSend:(NSInteger)totalBytesExpected {
GDataServiceTicketBase *ticket = [fetcher propertyForKey:kFetcherTicketKey];
[self invokeProgressCallbackForTicket:ticket
deliveredBytes:(unsigned long long)totalBytesSent
totalBytes:(unsigned long long)totalBytesExpected];
}
- (void)objectFetcher:(GTMBridgeFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *)error {
if (error) {
[self objectFetcher:fetcher failedWithData:data error:error];
return;
}
// we now have the XML data for a feed or entry
// save the current thread into the fetcher, since we'll handle additional
// fetches and callbacks on this thread
[fetcher setProperty:[NSThread currentThread]
forKey:kFetcherCallbackThreadKey];
// copy the run loop modes, if any, so we don't need to access them
// from the parsing thread
[fetcher setProperty:[[[self runLoopModes] copy] autorelease]
forKey:kFetcherCallbackRunLoopModesKey];
// we post parsing notifications now to ensure they're on caller's
// original thread
GDataServiceTicketBase *ticket = [fetcher propertyForKey:kFetcherTicketKey];
NSNotificationCenter *defaultNC = [NSNotificationCenter defaultCenter];
[defaultNC postNotificationName:kGDataServiceTicketParsingStartedNotification
object:ticket];
// if there's an operation queue, then use that to schedule parsing on another
// thread
SEL parseSel = @selector(parseObjectFromDataOfFetcher:);
if (operationQueue_ != nil) {
NSInvocationOperation *op;
op = [[[NSInvocationOperation alloc] initWithTarget:self
selector:parseSel
object:fetcher] autorelease];
[ticket setParseOperation:op];
[operationQueue_ addOperation:op];
// the fetcher now belongs to the parsing thread
} else {
// parse on the current thread, on Mac OS X 10.4 through 10.5.7
// or when the project defines GDATA_SKIP_PARSE_THREADING
[self performSelector:parseSel
withObject:fetcher];
}
}
- (void)parseObjectFromDataOfFetcher:(GTMBridgeFetcher *)fetcher {
// this may be invoked in a separate thread
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
#if GDATA_LOG_PERFORMANCE
NSTimeInterval secs1, secs2;
secs1 = [NSDate timeIntervalSinceReferenceDate];
#endif
NSError *error = nil;
GDataObject* object = nil;
// Generally protect the fetcher properties, since canceling a ticket would
// release the fetcher properties dictionary
#if !GTM_USE_SESSION_FETCHER
[[[fetcher properties] retain] autorelease];
#endif
// The callback thread is retaining the fetcher, so the fetcher shouldn't keep
// retaining the callback thread
NSThread *callbackThread = [fetcher propertyForKey:kFetcherCallbackThreadKey];
[[callbackThread retain] autorelease];
[fetcher setProperty:nil forKey:kFetcherCallbackThreadKey];
GDataServiceTicketBase *ticket = [fetcher propertyForKey:kFetcherTicketKey];
[[ticket retain] autorelease];
NSDictionary *responseHeaders = [fetcher responseHeaders];
[[responseHeaders retain] autorelease];
NSOperation *parseOperation = [ticket parseOperation];
Class objectClass = (Class)[fetcher propertyForKey:kFetcherObjectClassKey];
NSData *data = [fetcher downloadedData];
NSXMLDocument *xmlDocument = [[[NSXMLDocument alloc] initWithData:data
options:0
error:&error] autorelease];
if ([parseOperation isCancelled]) return;
if (xmlDocument) {
NSXMLElement* root = [xmlDocument rootElement];
if (!objectClass) {
objectClass = [GDataObject objectClassForXMLElement:root];
}
// see if the top-level class for the XML is listed in the surrogates;
// if so, instantiate the surrogate class instead
NSDictionary *surrogates = [ticket surrogates];
Class baseSurrogate = (Class)[surrogates objectForKey:objectClass];
if (baseSurrogate) {
objectClass = baseSurrogate;
}
// use the actual service version indicated by the response headers
NSString *serviceVersion = [responseHeaders objectForKey:@"Gdata-Version"];
// feeds may optionally be instantiated without unknown elements tracked
//
// we only ever want to fetch feeds and discard the unknown XML, never
// entries
BOOL shouldIgnoreUnknowns = ([ticket shouldFeedsIgnoreUnknowns]
&& [objectClass isSubclassOfClass:[GDataFeedBase class]]);
object = [[objectClass alloc] initWithXMLElement:root
parent:nil
serviceVersion:serviceVersion
surrogates:surrogates
shouldIgnoreUnknowns:shouldIgnoreUnknowns];
// we're done parsing; the extension declarations won't be needed again
[object clearExtensionDeclarationsCache];
#if GDATA_USES_LIBXML
// retain the document so that pointers to internal nodes remain valid
[object setProperty:xmlDocument forKey:kGDataXMLDocumentPropertyKey];
#endif
[fetcher setProperty:object forKey:kFetcherParsedObjectKey];
[object release];
#if GDATA_LOG_PERFORMANCE
secs2 = [NSDate timeIntervalSinceReferenceDate];
NSLog(@"allocation of %@ took %f seconds", objectClass, secs2 - secs1);
#endif
}
[fetcher setProperty:error forKey:kFetcherParseErrorKey];
if ([parseOperation isCancelled]) return;
SEL parseDoneSel = @selector(handleParsedObjectForFetcher:);
if (operationQueue_ != nil) {
NSArray *runLoopModes = [fetcher propertyForKey:kFetcherCallbackRunLoopModesKey];
if (runLoopModes) {
[self performSelector:parseDoneSel
onThread:callbackThread
withObject:fetcher
waitUntilDone:NO
modes:runLoopModes];
} else {
// defaults to common modes
[self performSelector:parseDoneSel
onThread:callbackThread
withObject:fetcher
waitUntilDone:NO];
}
// the fetcher now belongs to the callback thread
} else {
// in 10.4, there's no performSelector:onThread:
[self performSelector:parseDoneSel withObject:fetcher];
[fetcher setProperty:nil forKey:kFetcherCallbackThreadKey];
}
// We drain here to keep the clang static analyzer quiet.
[pool drain];
}
- (void)handleParsedObjectForFetcher:(GTMBridgeFetcher *)fetcher {
// after parsing is complete, this is invoked on the thread that the
// fetch was performed on
GDataServiceTicketBase *ticket = [fetcher propertyForKey:kFetcherTicketKey];
[ticket setParseOperation:nil];
// unpack the callback parameters
id delegate = [fetcher propertyForKey:kFetcherDelegateKey];
GDataObject *object = [fetcher propertyForKey:kFetcherParsedObjectKey];
NSError *error = [fetcher propertyForKey:kFetcherParseErrorKey];
SEL finishedSelector = NSSelectorFromString([fetcher propertyForKey:kFetcherFinishedSelectorKey]);
GDataServiceCompletionHandler completionHandler;
#if NS_BLOCKS_AVAILABLE
completionHandler = [fetcher propertyForKey:kFetcherCompletionHandlerKey];
#else
completionHandler = NULL;
#endif
NSNotificationCenter *defaultNC = [NSNotificationCenter defaultCenter];
[defaultNC postNotificationName:kGDataServiceTicketParsingStoppedNotification
object:ticket];
NSData *data = [fetcher downloadedData];
NSUInteger dataLength = [data length];
// if we created the object (or we got empty data back, as from a GData
// delete resource request) then we succeeded
if (object != nil || dataLength == 0) {
// if the user is fetching a feed and the ticket specifies that "next" links
// should be followed, then do that now
if ([ticket shouldFollowNextLinks]
&& [object isKindOfClass:[GDataFeedBase class]]) {
GDataFeedBase *latestFeed = (GDataFeedBase *)object;