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 pathGDataServiceGoogle.m
1444 lines (1159 loc) · 51.7 KB
/
GDataServiceGoogle.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.
*/
//
// GDataServiceGoogle.m
//
#define GDATASERVICEGOOGLE_DEFINE_GLOBALS 1
#import "GDataServiceGoogle.h"
#import "GDataAuthenticationFetcher.h"
extern NSString* const kFetcherRetryInvocationKey;
static NSString* const kCaptchaFullURLKey = @"CaptchaFullUrl";
static NSString* const kFetcherTicketKey = @"_ticket"; // same as in GDataServiceBase
static NSString* const kFetcherDependentInvocationsKey = @"_invocations";
static NSString* const kAuthDelegateKey = @"_delegate";
static NSString* const kAuthSelectorKey = @"_sel";
enum {
// indices of parameters for the post-authentication invocation,
// matching GDataServiceBase's method
// fetchObjectWithURL:objectClass:objectToPost:ETag:httpMethod:delegate:didFinishSelector:completionHandler:retryInvocationValue:ticket:
kInvocationObjectURLIndex = 2,
kInvocationObjectClassIndex,
kInvocationObjectToPostIndex,
kInvocationObjectETagIndex,
kInvocationHTTPMethodIndex,
kInvocationDelegateIndex,
kInvocationFinishedSelectorIndex,
kInvocationCompletionHandlerIndex,
kInvocationRetryInvocationValueIndex,
kInvocationTicketIndex
};
@interface GDataServiceBase (ProtectedMethods)
- (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
retryInvocationValue:(NSValue *)retryInvocationValue
ticket:(GDataServiceTicketBase *)ticket;
@end
@interface GDataServiceGoogle (PrivateMethods)
- (GTMBridgeFetcher *)authenticationFetcher;
- (NSError *)cannotCreateAuthFetcherError;
- (GDataServiceTicket *)deferUntilAuthenticationForInvocation:(NSInvocation *)invocation;
- (void)authFetcher:(GTMBridgeFetcher *)fetcher failedWithError:(NSError *)error data:(NSData *)data;
- (NSError *)errorForAuthFetcherStatus:(NSInteger)status data:(NSData *)data;
- (void)authFetcher:(GTMBridgeFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *)error;
- (BOOL)authFetcher:(GTMBridgeFetcher *)fetcher willRetry:(BOOL)willRetry forError:(NSError *)error;
- (void)standaloneAuthFetcher:(GTMBridgeFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *)error;
- (void)standaloneAuthFetcher:(GTMBridgeFetcher *)fetcher failedWithError:(NSError *)error data:(NSData *)data;
- (void)addNamespacesIfNoneToObject:(GDataObject *)obj;
@end
@implementation GDataServiceGoogle
+ (Class)ticketClass {
return [GDataServiceTicket class];
}
- (void)dealloc {
[captchaToken_ release];
[captchaAnswer_ release];
[authToken_ release];
[authSubToken_ release];
[accountType_ release];
[signInDomain_ release];
[serviceID_ release];
[pendingAuthFetcher_ release];
[credentialDate_ release];
[super dealloc];
}
#pragma mark -
- (NSDictionary *)customAuthenticationRequestHeaders {
// subclasses may override
return nil;
}
- (GTMBridgeFetcher *)authenticationFetcher {
// internal routine
//
// create and return an authentication fetcher, either for use alone or as
// part of a GData object fetch sequence
NSDictionary *customHeaders = [self customAuthenticationRequestHeaders];
NSString *domain = [self signInDomain];
NSString *serviceID = [self serviceID];
NSString *accountType = [self accountType];
NSString *password = [self password];
NSString *userAgent = [self userAgent];
if ([userAgent length] == 0) {
userAgent = [[self class] defaultApplicationIdentifier];
}
NSDictionary *captchaDict = nil;
if ([captchaToken_ length] > 0 && [captchaAnswer_ length] > 0) {
captchaDict = [NSDictionary dictionaryWithObjectsAndKeys:
captchaToken_, @"logintoken",
captchaAnswer_, @"logincaptcha", nil];
}
GTMBridgeFetcher *fetcher;
fetcher = [GDataAuthenticationFetcher authTokenFetcherWithUsername:username_
password:password
service:serviceID
source:userAgent
signInDomain:domain
accountType:accountType
additionalParameters:captchaDict
customHeaders:customHeaders];
#if !GTM_USE_SESSION_FETCHER
[fetcher setRunLoopModes:[self runLoopModes]];
[fetcher setFetchHistory:[fetcherService_ fetchHistory]];
#endif
[fetcher setAllowedInsecureSchemes:[fetcherService_ allowedInsecureSchemes]];
[fetcher setAllowLocalhostRequest:[fetcherService_ allowLocalhostRequest]];
[fetcher setRetryEnabled:[self isServiceRetryEnabled]];
[fetcher setMaxRetryInterval:[self serviceMaxRetryInterval]];
// note: this does not use the custom serviceRetrySelector, as that
// assumes there is a ticket associated with the fetcher
return fetcher;
}
- (NSError *)cannotCreateAuthFetcherError {
NSDictionary *userInfo;
userInfo = [NSDictionary dictionaryWithObject:@"empty username/password"
forKey:kGDataServerErrorStringKey];
NSError *error = [NSError errorWithDomain:kGDataServiceErrorDomain
code:-1
userInfo:userInfo];
return error;
}
- (void)addDependentInvocation:(NSInvocation *)invocation
toAuthFetcher:(GTMBridgeFetcher *)fetcher {
// add the invocation to the list in the fetcher's properties
NSMutableArray *array = [fetcher propertyForKey:kFetcherDependentInvocationsKey];
if (array == nil) {
array = [NSMutableArray arrayWithObject:invocation];
[fetcher setProperty:array
forKey:kFetcherDependentInvocationsKey];
} else {
[array addObject:invocation];
}
}
// This routine creates a new auth fetcher, and saves the invocation in the
// list of dependencies to call when the auth fetcher completes
- (GDataServiceTicket *)authenticateThenInvoke:(NSInvocation *)invocation {
// this method always creates a new auth fetcher, so there should be none
// already pending
GDATA_DEBUG_ASSERT([self pendingAuthFetcher] == nil,
@"unexpected auth fetcher");
GDataServiceTicket *ticket;
[invocation getArgument:&ticket atIndex:kInvocationTicketIndex];
GTMBridgeFetcher *fetcher = [self authenticationFetcher];
if (fetcher) {
[self addDependentInvocation:invocation
toAuthFetcher:fetcher];
// store the ticket in the same property the base class uses when
// fetching so that notification-time code can find the ticket easily
[fetcher setProperty:ticket
forKey:kFetcherTicketKey];
if ([ticket retrySelector]) {
#if GTM_USE_SESSION_FETCHER
__block GTMBridgeFetcher *fetcherRef = fetcher;
fetcher.retryBlock = ^(BOOL suggestedWillRetry, NSError *error,
GTMSessionFetcherRetryResponse response) {
BOOL shouldRetry = [self authFetcher:fetcherRef
willRetry:suggestedWillRetry
forError:error];
response(shouldRetry);
};
#else
[fetcher setRetrySelector:@selector(authFetcher:willRetry:forError:)];
#endif
}
[ticket setAuthFetcher:fetcher];
[ticket setCurrentFetcher:fetcher];
[self setPendingAuthFetcher:fetcher];
[fetcher setComment:@"API authentication"];
[fetcher beginFetchWithDelegate:self
didFinishSelector:@selector(authFetcher:finishedWithData:error:)];
return ticket;
} else {
// we could not initiate a fetch; tell the client
id delegate;
SEL finishedSelector;
[invocation getArgument:&delegate atIndex:kInvocationDelegateIndex];
[invocation getArgument:&finishedSelector atIndex:kInvocationFinishedSelectorIndex];
NSError *error = [self cannotCreateAuthFetcherError];
if (finishedSelector) {
[[self class] invokeCallback:finishedSelector
target:delegate
ticket:ticket
object:nil
error:error];
}
#if NS_BLOCKS_AVAILABLE
GDataServiceGoogleCompletionHandler completionHandler;
[invocation getArgument:&completionHandler
atIndex:kInvocationCompletionHandlerIndex];
if (completionHandler) {
completionHandler(ticket, nil, error);
}
#endif
return nil;
}
}
- (void)authFetcher:(GTMBridgeFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *)error {
if (error) {
[self authFetcher:fetcher failedWithError:error data:data];
return;
}
// authentication fetch completed
NSDictionary *responseDict = [GDataUtilities dictionaryWithResponseData:data];
NSString *authToken = [responseDict objectForKey:kGDataServiceAuthTokenKey];
// if this is the pending auth fetcher, save the token for future auths
if (fetcher == [self pendingAuthFetcher]) {
[self setAuthToken:authToken];
[self setPendingAuthFetcher:nil];
}
if ([authToken length] > 0) {
// there was an auth token, so iterate through the callbacks
NSArray *dependentInvocations = [fetcher propertyForKey:kFetcherDependentInvocationsKey];
for (NSInvocation *invocation in dependentInvocations) {
// set the ticket's currentFetcher to nil before we invoke the fetch of
// the GData object so the user won't mistakenly see indication that
// the auth fetch is still in progress
GDataServiceTicket *ticket;
[invocation getArgument:&ticket atIndex:kInvocationTicketIndex];
[ticket setCurrentFetcher:nil];
[ticket setAuthToken:authToken];
[invocation invoke];
}
} else {
// there was no auth token
NSDictionary *userInfo;
userInfo = [NSDictionary dictionaryWithObject:data
forKey:kGDataFetcherStatusDataKey];
NSError *error = [NSError errorWithDomain:kGTMBridgeFetcherStatusDomain
code:kGDataFetcherStatusForbidden
userInfo:userInfo];
[self authFetcher:fetcher failedWithError:error data:data];
}
// the properties contain the ticket which points to the
// fetcher; free those now to break the retain cycle
[fetcher setProperties:nil];
}
- (void)authFetcher:(GTMBridgeFetcher *)fetcher failedWithError:(NSError *)error data:(NSData *)data {
if (fetcher == [self pendingAuthFetcher]) {
[self setAuthToken:nil];
[self setPendingAuthFetcher:nil];
}
if ([[error domain] isEqual:kGTMBridgeFetcherStatusDomain]) {
NSInteger status = [error code];
error = [self errorForAuthFetcherStatus:status data:data];
}
// iterate through the callbacks to tell each that the fetch failed
NSArray *dependentInvocations = [[[fetcher propertyForKey:kFetcherDependentInvocationsKey] retain] autorelease];
[fetcher setProperties:nil];
for (NSInvocation *invocation in dependentInvocations) {
id delegate;
SEL finishedSelector;
GDataServiceTicket *ticket;
[invocation getArgument:&delegate atIndex:kInvocationDelegateIndex];
[invocation getArgument:&finishedSelector atIndex:kInvocationFinishedSelectorIndex];
[invocation getArgument:&ticket atIndex:kInvocationTicketIndex];
if (finishedSelector) {
[[self class] invokeCallback:finishedSelector
target:delegate
ticket:ticket
object:nil
error:error];
}
#if NS_BLOCKS_AVAILABLE
GDataServiceGoogleCompletionHandler completionHandler;
[invocation getArgument:&completionHandler
atIndex:kInvocationCompletionHandlerIndex];
if (completionHandler) {
completionHandler(ticket, nil, error);
}
#endif
[ticket setFetchError:error];
[ticket setHasCalledCallback:YES];
[ticket setCurrentFetcher:nil];
}
}
- (NSError *)errorForAuthFetcherStatus:(NSInteger)status data:(NSData *)data {
// convert the data into a useful NSError
NSMutableDictionary *userInfo = nil;
if ([data length] > 0) {
// put user-readable error info into the error object
NSDictionary *responseDict = [GDataUtilities dictionaryWithResponseData:data];
userInfo = [NSMutableDictionary dictionaryWithDictionary:responseDict];
// look for the partial-path URL to a captch image (which the user
// can retrieve from the userInfo later with the -captchaURL method)
NSString *str = [userInfo objectForKey:@"CaptchaUrl"];
if ([str length] > 0) {
// since we know the sign-in domain now, make a string with the full URL
NSString *captchaURLString;
if ([str hasPrefix:@"http:"] || [str hasPrefix:@"https:"]) {
// the server gave us a full URL
captchaURLString = str;
} else {
// the server gave us a relative URL
captchaURLString = [NSString stringWithFormat:@"https://%@/accounts/%@",
[self signInDomain], str];
}
[userInfo setObject:captchaURLString forKey:kCaptchaFullURLKey];
}
// The auth server returns errors as "Error" but generally the library
// provides errors in the userInfo as "error". We'll copy over the
// auth server's error to "error" as a convenience to clients, and hope
// few are confused about why the error appears twice in the dictionary.
NSString *authErrStr = [userInfo authenticationError];
if (authErrStr != nil
&& [userInfo objectForKey:kGDataServerErrorStringKey] == nil) {
[userInfo setObject:authErrStr forKey:kGDataServerErrorStringKey];
}
// copy additional error info into the NSError key so it shows up in the
// error description string
NSString *authInfoStr = [userInfo objectForKey:kGDataServerInfoStringKey];
if (authInfoStr != nil) {
[userInfo setObject:authInfoStr forKey:NSLocalizedFailureReasonErrorKey];
}
}
NSError *error = [NSError errorWithDomain:kGDataServiceErrorDomain
code:status
userInfo:userInfo];
return error;
}
// The auth fetcher may call into this retry method; this one invokes the
// first retry selector found among the tickets dependent on this auth fetcher
- (BOOL)authFetcher:(GTMBridgeFetcher *)fetcher willRetry:(BOOL)willRetry forError:(NSError *)error {
NSArray *dependentInvocations = [fetcher propertyForKey:kFetcherDependentInvocationsKey];
for (NSInvocation *invocation in dependentInvocations) {
id delegate;
GDataServiceTicket *ticket;
[invocation getArgument:&delegate atIndex:kInvocationDelegateIndex];
[invocation getArgument:&ticket atIndex:kInvocationTicketIndex];
SEL retrySelector = [ticket retrySelector];
if (retrySelector) {
willRetry = [self invokeRetrySelector:retrySelector
delegate:delegate
ticket:ticket
willRetry:willRetry
error:error];
break;
}
}
return willRetry;
}
// This is the main routine for invoking transactions with with Google services.
// If there is no auth token available, this routine authenticates before invoking
// the action.
- (GDataServiceTicket *)fetchAuthenticatedObjectWithURL:(NSURL *)objectURL
objectClass:(Class)objectClass
objectToPost:(GDataObject *)objectToPost
ETag:(NSString *)etag
httpMethod:(NSString *)httpMethod
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector
completionHandler:(GDataServiceGoogleCompletionHandler)completionHandler {
// make an invocation for this call
GDataServiceTicket *result = nil;
SEL theSEL = @selector(fetchObjectWithURL:objectClass:objectToPost:ETag:httpMethod:delegate:didFinishSelector:completionHandler:retryInvocationValue:ticket:);
GDataServiceTicket *ticket = [GDataServiceTicket ticketForService:self];
if (objectToPost) {
// be sure the postedObject is available to the callbacks even if we fail
// in authenticating, before getting around to trying to upload it
[ticket setPostedObject:objectToPost];
}
#if NS_BLOCKS_AVAILABLE
if (completionHandler) {
// copy the completion handler to the heap now, before creating the
// invocation that will retain it
completionHandler = [[completionHandler copy] autorelease];
}
#endif
NSMethodSignature *signature = [self methodSignatureForSelector:theSEL];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:theSEL];
[invocation setTarget:self];
[invocation setArgument:&objectURL atIndex:kInvocationObjectURLIndex];
[invocation setArgument:&objectClass atIndex:kInvocationObjectClassIndex];
[invocation setArgument:&objectToPost atIndex:kInvocationObjectToPostIndex];
[invocation setArgument:&etag atIndex:kInvocationObjectETagIndex];
[invocation setArgument:&httpMethod atIndex:kInvocationHTTPMethodIndex];
[invocation setArgument:&delegate atIndex:kInvocationDelegateIndex];
[invocation setArgument:&finishedSelector atIndex:kInvocationFinishedSelectorIndex];
[invocation setArgument:&completionHandler atIndex:kInvocationCompletionHandlerIndex];
[invocation setArgument:&ticket atIndex:kInvocationTicketIndex];
NSValue *noRetryInvocation = nil;
[invocation setArgument:&noRetryInvocation atIndex:kInvocationRetryInvocationValueIndex];
[invocation retainArguments];
if ([username_ length] == 0) {
// There's no username, so we can proceed to fetch. We won't be retrying
// this invocation if it fails.
[invocation invoke];
[invocation getReturnValue:&result];
} else if ([[ticket authToken] length] > 0 || [authSubToken_ length] > 0) {
// There is already an auth token.
//
// If the auth token has expired, we'll be retrying this same invocation
// after getting a fresh token
// Having the invocation retain itself as a parameter would cause a
// retain loop, so we'll have it retain an NSValue of itself
NSValue *invocationValue = [NSValue valueWithNonretainedObject:invocation];
[invocation setArgument:&invocationValue
atIndex:kInvocationRetryInvocationValueIndex];
[invocation invoke];
[invocation getReturnValue:&result];
} else {
// we need to authenticate first. We won't be retrying this invocation if
// it fails.
result = [self deferUntilAuthenticationForInvocation:invocation];
}
return result;
}
- (GDataServiceTicket *)deferUntilAuthenticationForInvocation:(NSInvocation *)invocation {
GDataServiceTicket *ticket = nil;
GTMBridgeFetcher *pendingAuthFetcher = [self pendingAuthFetcher];
if (pendingAuthFetcher == nil) {
// there is no pending auth fetcher, so create a new one
ticket = [self authenticateThenInvoke:invocation];
} else {
// there is already an auth fetcher pending; make this fetch
// dependent on it
[self addDependentInvocation:invocation
toAuthFetcher:pendingAuthFetcher];
[invocation getArgument:&ticket atIndex:kInvocationTicketIndex];
[ticket setAuthFetcher:pendingAuthFetcher];
[ticket setCurrentFetcher:pendingAuthFetcher];
}
return ticket;
}
// override the base class's failure handler to look for a session expired error
- (void)objectFetcher:(GTMBridgeFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *)error {
// check for an expired token
NSInteger code = [error code];
if (code == kGDataFetcherStatusUnauthorized
|| code == kGDataFetcherStatusForbidden) {
NSInvocation *retryInvocation = [fetcher propertyForKey:kFetcherRetryInvocationKey];
if (retryInvocation) {
// clear out the ticket's auth token
GDataServiceTicket *ticket = nil;
[retryInvocation getArgument:&ticket atIndex:kInvocationTicketIndex];
[ticket setAuthToken:nil];
// avoid an infinite loop: remove the retry invocation before re-invoking
NSValue *noRetryInvocation = nil;
[retryInvocation setArgument:&noRetryInvocation
atIndex:kInvocationRetryInvocationValueIndex];
// if the credential has changed, we don't want to try reauthentication
// since it would be with a different username and password
if (AreEqualOrBothNil([self credentialDate], [ticket credentialDate])) {
[self deferUntilAuthenticationForInvocation:retryInvocation];
return;
}
}
}
[super objectFetcher:fetcher finishedWithData:data error:error];
}
- (void)stopAuthenticationForTicket:(GDataServiceTicket *)ticket {
// remove this ticket from the auth fetcher's list of ticket invocations
GTMBridgeFetcher *authFetcher = [ticket authFetcher];
// find this ticket's invocation in the auth fetcher's dependencies
NSMutableArray *dependentInvocations = [authFetcher propertyForKey:kFetcherDependentInvocationsKey];
for (NSInvocation *invocation in dependentInvocations) {
// get the ticket from the invocation's arguments
GDataServiceTicket *invTicket;
[invocation getArgument:&invTicket atIndex:kInvocationTicketIndex];
if (ticket == invTicket) {
// we found the desired ticket; remove it from the list of dependents
[dependentInvocations removeObject:invocation];
break;
}
}
if ([dependentInvocations count] == 0) {
// this was the only dependent invocation, so we can discard the auth
// fetcher
[authFetcher stopFetching];
[authFetcher setProperty:nil
forKey:kFetcherDependentInvocationsKey];
if (authFetcher == [self pendingAuthFetcher]) {
[self setPendingAuthFetcher:nil];
}
}
// this ticket no longer has an associated auth fetcher
[ticket setAuthFetcher:nil];
}
#pragma mark -
// Standalone auth: authenticate without fetching a feed or entry
//
// authSelector has a signature matching:
// - (void)ticket:(GDataServiceTicket *)ticket authenticatedWithError:(NSError *)error;
- (GDataServiceTicket *)authenticateWithDelegate:(id)delegate
didAuthenticateSelector:(SEL)authSelector {
GTMBridgeAssertValidSelector(delegate, authSelector, @encode(GDataServiceGoogle *), @encode(NSError *), 0);
// make a new auth fetcher
GTMBridgeFetcher *fetcher = [self authenticationFetcher];
if (fetcher) {
NSString *selStr = NSStringFromSelector(authSelector);
[fetcher setProperty:delegate forKey:kAuthDelegateKey];
[fetcher setProperty:selStr forKey:kAuthSelectorKey];
GDataServiceTicket *ticket = [GDataServiceTicket ticketForService:self];
[ticket setAuthFetcher:fetcher];
[fetcher setProperty:ticket forKey:kFetcherTicketKey];
[fetcher setComment:@"API authentication"];
BOOL flag = YES;
#if GTM_USE_SESSION_FETCHER
[fetcher beginFetchWithDelegate:self
didFinishSelector:@selector(standaloneAuthFetcher:finishedWithData:error:)];
#else
flag = [fetcher beginFetchWithDelegate:self
didFinishSelector:@selector(standaloneAuthFetcher:finishedWithData:error:)];
#endif
if (flag) {
return ticket;
} else {
// failed to start the fetch; the fetch failed callback was called
return nil;
}
}
// we could not initiate a fetch; tell the client
if (authSelector) {
NSError *error = [self cannotCreateAuthFetcherError];
[delegate performSelector:authSelector
withObject:nil
withObject:error];
}
return nil;
}
- (void)standaloneAuthFetcher:(GTMBridgeFetcher *)fetcher
finishedWithData:(NSData *)data
error:(NSError *)error {
if (error) {
[self standaloneAuthFetcher:fetcher failedWithError:error data:data];
return;
}
NSDictionary *responseDict = [GDataUtilities dictionaryWithResponseData:data];
NSString *authToken = [responseDict objectForKey:kGDataServiceAuthTokenKey];
// save the new auth token, even if it's empty
[self setAuthToken:authToken];
GDataServiceTicket *ticket = [fetcher propertyForKey:kFetcherTicketKey];
[ticket setAuthToken:authToken];
NSString *selStr = [fetcher propertyForKey:kAuthSelectorKey];
id delegate = [fetcher propertyForKey:kAuthDelegateKey];
SEL authSelector = NSSelectorFromString(selStr);
if ([authToken length] > 0) {
// succeeded
if (authSelector) {
[delegate performSelector:authSelector
withObject:ticket
withObject:nil];
}
[ticket setAuthFetcher:nil];
// avoid a retain cycle
[fetcher setProperties:nil];
} else {
// failed: there was no auth token
NSError *error = [self errorForAuthFetcherStatus:kGDataFetcherStatusForbidden
data:data];
[self standaloneAuthFetcher:fetcher failedWithError:error data:data];
}
}
- (void)standaloneAuthFetcher:(GTMBridgeFetcher *)fetcher
failedWithError:(NSError *)error
data:(NSData *)data {
// failed to authenticate
if ([[error domain] isEqual:kGTMBridgeFetcherStatusDomain]) {
NSInteger status = [error code];
error = [self errorForAuthFetcherStatus:status data:data];
}
NSString *selStr = [fetcher propertyForKey:kAuthSelectorKey];
id delegate = [fetcher propertyForKey:kAuthDelegateKey];
SEL authSelector = NSSelectorFromString(selStr);
GDataServiceTicket *ticket = [fetcher propertyForKey:kFetcherTicketKey];
[delegate performSelector:authSelector
withObject:ticket
withObject:error];
[ticket setAuthFetcher:nil];
// avoid a retain cycle
[fetcher setProperties:nil];
}
#pragma mark -
- (GDataServiceTicket *)fetchFeedWithURL:(NSURL *)feedURL
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
return [self fetchFeedWithURL:feedURL
feedClass:kGDataUseRegisteredClass
ETag:nil
delegate:delegate
didFinishSelector:finishedSelector];
}
- (GDataServiceTicket *)fetchFeedWithURL:(NSURL *)feedURL
feedClass:(Class)feedClass
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
return [self fetchFeedWithURL:feedURL
feedClass:feedClass
ETag:nil
delegate:delegate
didFinishSelector:finishedSelector];
}
- (GDataServiceTicket *)fetchFeedWithURL:(NSURL *)feedURL
feedClass:(Class)feedClass
ETag:(NSString *)etag
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
return [self fetchAuthenticatedObjectWithURL:feedURL
objectClass:feedClass
objectToPost:nil
ETag:etag
httpMethod:nil
delegate:delegate
didFinishSelector:finishedSelector
completionHandler:NULL];
}
- (GDataServiceTicket *)fetchEntryWithURL:(NSURL *)entryURL
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
return [self fetchEntryWithURL:entryURL
entryClass:kGDataUseRegisteredClass
ETag:nil
delegate:delegate
didFinishSelector:finishedSelector];
}
- (GDataServiceTicket *)fetchEntryWithURL:(NSURL *)entryURL
entryClass:(Class)entryClass
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
return [self fetchEntryWithURL:entryURL
entryClass:entryClass
ETag:nil
delegate:delegate
didFinishSelector:finishedSelector];
}
- (GDataServiceTicket *)fetchEntryWithURL:(NSURL *)entryURL
entryClass:(Class)entryClass
ETag:(NSString *)etag
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
return [self fetchAuthenticatedObjectWithURL:entryURL
objectClass:entryClass
objectToPost:nil
ETag:etag
httpMethod:nil
delegate:delegate
didFinishSelector:finishedSelector
completionHandler:NULL];
}
- (GDataServiceTicket *)fetchEntryByInsertingEntry:(GDataEntryBase *)entryToInsert
forFeedURL:(NSURL *)feedURL
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
NSString *etag = [entryToInsert ETag];
// objects being uploaded will always need some namespaces at the root level
[self addNamespacesIfNoneToObject:entryToInsert];
return [self fetchAuthenticatedObjectWithURL:feedURL
objectClass:[entryToInsert class]
objectToPost:entryToInsert
ETag:etag
httpMethod:@"POST"
delegate:delegate
didFinishSelector:finishedSelector
completionHandler:NULL];
}
- (GDataServiceTicket *)fetchEntryByUpdatingEntry:(GDataEntryBase *)entryToUpdate
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
NSURL *editURL = [[entryToUpdate editLink] URL];
return [self fetchEntryByUpdatingEntry:entryToUpdate
forEntryURL:editURL
delegate:delegate
didFinishSelector:finishedSelector];
}
- (GDataServiceTicket *)fetchEntryByUpdatingEntry:(GDataEntryBase *)entryToUpdate
forEntryURL:(NSURL *)entryURL
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
// Entries should be updated only if they contain copies of any unparsed XML
// (unknown children and attributes) or if fields to update are explicitly
// specified in the gd:field attribute.
//
// To update all fields of an entry that ignores unparsed XML, first fetch a
// complete copy with fetchEntryWithURL: (or a service-specific entry fetch
// method) using the URL from the entry's selfLink.
//
// See setShouldServiceFeedsIgnoreUnknowns in GDataServiceBase.h for more
// information.
NSString *fieldSelection = [entryToUpdate fieldSelection];
GDATA_ASSERT(fieldSelection != nil || ![entryToUpdate shouldIgnoreUnknowns],
@"unsafe update of %@", [entryToUpdate class]);
// objects being uploaded will always need some namespaces at the root level
[self addNamespacesIfNoneToObject:entryToUpdate];
NSString *httpMethod = (fieldSelection == nil ? @"PUT" : @"PATCH");
return [self fetchAuthenticatedObjectWithURL:entryURL
objectClass:[entryToUpdate class]
objectToPost:entryToUpdate
ETag:[entryToUpdate ETag]
httpMethod:httpMethod
delegate:delegate
didFinishSelector:finishedSelector
completionHandler:NULL];
}
- (GDataServiceTicket *)deleteEntry:(GDataEntryBase *)entryToDelete
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
NSString *etag = [entryToDelete ETag];
NSURL *editURL = [[entryToDelete editLink] URL];
GDATA_ASSERT(editURL != nil, @"deleting uneditable entry: %@", entryToDelete);
GDataServiceTicket *ticket = [self deleteResourceURL:editURL
ETag:etag
delegate:delegate
didFinishSelector:finishedSelector];
// we'll put the entry being deleted into the ticket's postedObject property
// as a convenience to the caller even though we're not really posting an
// object
[ticket setPostedObject:entryToDelete];
return ticket;
}
- (GDataServiceTicket *)deleteResourceURL:(NSURL *)resourceEditURL
ETag:(NSString *)etag
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
GDATA_ASSERT(resourceEditURL != nil, @"deleting unspecified resource");
return [self fetchAuthenticatedObjectWithURL:resourceEditURL
objectClass:nil
objectToPost:nil
ETag:etag
httpMethod:@"DELETE"
delegate:delegate
didFinishSelector:finishedSelector
completionHandler:NULL];
}
- (GDataServiceTicket *)fetchFeedWithQuery:(GDataQuery *)query
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
return [self fetchFeedWithURL:[query URL]
feedClass:kGDataUseRegisteredClass
delegate:delegate
didFinishSelector:finishedSelector];
}
- (GDataServiceTicket *)fetchFeedWithQuery:(GDataQuery *)query
feedClass:(Class)feedClass
delegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
return [self fetchFeedWithURL:[query URL]
feedClass:feedClass
delegate:delegate
didFinishSelector:finishedSelector];
}
#pragma mark -
#if NS_BLOCKS_AVAILABLE
- (GDataServiceTicket *)fetchFeedWithURL:(NSURL *)feedURL
completionHandler:(GDataServiceGoogleFeedBaseCompletionHandler)handler {
return [self fetchAuthenticatedObjectWithURL:feedURL
objectClass:kGDataUseRegisteredClass
objectToPost:nil
ETag:nil
httpMethod:nil
delegate:nil
didFinishSelector:NULL
completionHandler:(GDataServiceGoogleCompletionHandler)handler];
}
- (GDataServiceTicket *)fetchFeedWithQuery:(GDataQuery *)query
completionHandler:(void (^)(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error))handler {
return [self fetchFeedWithURL:[query URL]
completionHandler:handler];
}
- (GDataServiceTicket *)fetchEntryWithURL:(NSURL *)entryURL
entryClass:(Class)entryClass
completionHandler:(GDataServiceGoogleEntryBaseCompletionHandler)handler {
return [self fetchAuthenticatedObjectWithURL:entryURL
objectClass:entryClass
objectToPost:nil
ETag:nil
httpMethod:nil
delegate:nil
didFinishSelector:NULL
completionHandler:(GDataServiceGoogleCompletionHandler)handler];
}
- (GDataServiceTicket *)fetchEntryWithURL:(NSURL *)entryURL
completionHandler:(GDataServiceGoogleEntryBaseCompletionHandler)handler {
return [self fetchEntryWithURL:entryURL
entryClass:kGDataUseRegisteredClass
completionHandler:handler];
}
- (GDataServiceTicket *)fetchEntryByInsertingEntry:(GDataEntryBase *)entryToInsert
forFeedURL:(NSURL *)feedURL
completionHandler:(GDataServiceGoogleEntryBaseCompletionHandler)handler {
NSString *etag = [entryToInsert ETag];
// objects being uploaded will always need some namespaces at the root level
[self addNamespacesIfNoneToObject:entryToInsert];
return [self fetchAuthenticatedObjectWithURL:feedURL
objectClass:[entryToInsert class]
objectToPost:entryToInsert
ETag:etag
httpMethod:@"POST"
delegate:nil
didFinishSelector:NULL
completionHandler:(GDataServiceGoogleCompletionHandler)handler];