-
Notifications
You must be signed in to change notification settings - Fork 164
/
MGTwitterEngine.m
2168 lines (1705 loc) · 75 KB
/
MGTwitterEngine.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
//
// MGTwitterEngine.m
// MGTwitterEngine
//
// Created by Matt Gemmell on 10/02/2008.
// Copyright 2008 Instinctive Code.
//
#import "MGTwitterEngine.h"
#import "MGTwitterHTTPURLConnection.h"
#import "OAuthConsumer.h"
#import "NSData+Base64.h"
#ifndef USE_LIBXML
// if you wish to use LibXML, add USE_LIBXML=1 to "Precompiler Macros" in Project Info for all targets
# define USE_LIBXML 0
#endif
#if YAJL_AVAILABLE
#define API_FORMAT @"json"
#import "MGTwitterStatusesYAJLParser.h"
#import "MGTwitterMessagesYAJLParser.h"
#import "MGTwitterUsersYAJLParser.h"
#import "MGTwitterMiscYAJLParser.h"
#import "MGTwitterSearchYAJLParser.h"
#elif TOUCHJSON_AVAILABLE
#define API_FORMAT @"json"
#import "MGTwitterTouchJSONParser.h"
#else
#define API_FORMAT @"xml"
#if USE_LIBXML
#import "MGTwitterStatusesLibXMLParser.h"
#import "MGTwitterMessagesLibXMLParser.h"
#import "MGTwitterUsersLibXMLParser.h"
#import "MGTwitterMiscLibXMLParser.h"
#import "MGTwitterSocialGraphLibXMLParser.h"
#else
#import "MGTwitterStatusesParser.h"
#import "MGTwitterUsersParser.h"
#import "MGTwitterMessagesParser.h"
#import "MGTwitterMiscParser.h"
#import "MGTwitterSocialGraphParser.h"
#import "MGTwitterUserListsParser.h"
#endif
#endif
#define TWITTER_DOMAIN @"api.twitter.com/1"
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
#define TWITTER_SEARCH_DOMAIN @"search.twitter.com"
#endif
#define HTTP_POST_METHOD @"POST"
#define MAX_MESSAGE_LENGTH 140 // Twitter recommends tweets of max 140 chars
#define MAX_NAME_LENGTH 20
#define MAX_EMAIL_LENGTH 40
#define MAX_URL_LENGTH 100
#define MAX_LOCATION_LENGTH 30
#define MAX_DESCRIPTION_LENGTH 160
#define DEFAULT_CLIENT_NAME @"MGTwitterEngine"
#define DEFAULT_CLIENT_VERSION @"1.0"
#define DEFAULT_CLIENT_URL @"http://mattgemmell.com/source"
#define DEFAULT_CLIENT_TOKEN @"mgtwitterengine"
#define URL_REQUEST_TIMEOUT 25.0 // Twitter usually fails quickly if it's going to fail at all.
@interface NSDictionary (MGTwitterEngineExtensions)
-(NSDictionary *)MGTE_dictionaryByRemovingObjectForKey:(NSString *)key;
@end
@implementation NSDictionary (MGTwitterEngineExtensions)
-(NSDictionary *)MGTE_dictionaryByRemovingObjectForKey:(NSString *)key{
NSDictionary *result = self;
if(key){
NSMutableDictionary *newParams = [[self mutableCopy] autorelease];
[newParams removeObjectForKey:key];
result = [[newParams copy] autorelease];
}
return result;
}
@end
@interface MGTwitterEngine (PrivateMethods)
// Utility methods
- (NSDateFormatter *)_HTTPDateFormatter;
- (NSString *)_queryStringWithBase:(NSString *)base parameters:(NSDictionary *)params prefixed:(BOOL)prefixed;
- (NSDate *)_HTTPToDate:(NSString *)httpDate;
- (NSString *)_dateToHTTP:(NSDate *)date;
- (NSString *)_encodeString:(NSString *)string;
// Connection/Request methods
- (NSString*)_sendRequest:(NSURLRequest *)theRequest withRequestType:(MGTwitterRequestType)requestType responseType:(MGTwitterResponseType)responseType;
- (NSString *)_sendRequestWithMethod:(NSString *)method
path:(NSString *)path
queryParameters:(NSDictionary *)params
body:(NSString *)body
requestType:(MGTwitterRequestType)requestType
responseType:(MGTwitterResponseType)responseType;
- (NSString *)_sendDataRequestWithMethod:(NSString *)method
path:(NSString *)path
queryParameters:(NSDictionary *)params
filePath:(NSString *)filePath
body:(NSString *)body
requestType:(MGTwitterRequestType)requestType
responseType:(MGTwitterResponseType)responseType;
- (NSMutableURLRequest *)_baseRequestWithMethod:(NSString *)method
path:(NSString *)path
requestType:(MGTwitterRequestType)requestType
queryParameters:(NSDictionary *)params;
// Parsing methods
- (void)_parseDataForConnection:(MGTwitterHTTPURLConnection *)connection;
// Delegate methods
- (BOOL) _isValidDelegateForSelector:(SEL)selector;
@end
@implementation MGTwitterEngine
#pragma mark Constructors
+ (MGTwitterEngine *)twitterEngineWithDelegate:(NSObject *)theDelegate
{
return [[[self alloc] initWithDelegate:theDelegate] autorelease];
}
- (MGTwitterEngine *)initWithDelegate:(NSObject *)newDelegate
{
if ((self = [super init])) {
_delegate = newDelegate; // deliberately weak reference
_connections = [[NSMutableDictionary alloc] initWithCapacity:0];
_clientName = [DEFAULT_CLIENT_NAME retain];
_clientVersion = [DEFAULT_CLIENT_VERSION retain];
_clientURL = [DEFAULT_CLIENT_URL retain];
_clientSourceToken = [DEFAULT_CLIENT_TOKEN retain];
_APIDomain = [TWITTER_DOMAIN retain];
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
_searchDomain = [TWITTER_SEARCH_DOMAIN retain];
#endif
_secureConnection = YES;
_clearsCookies = NO;
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
_deliveryOptions = MGTwitterEngineDeliveryAllResultsOption;
#endif
}
return self;
}
- (void)dealloc
{
_delegate = nil;
[[_connections allValues] makeObjectsPerformSelector:@selector(cancel)];
[_connections release];
[_username release];
[_password release];
[_clientName release];
[_clientVersion release];
[_clientURL release];
[_clientSourceToken release];
[_APIDomain release];
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
[_searchDomain release];
#endif
[super dealloc];
}
#pragma mark Configuration and Accessors
+ (NSString *)version
{
// 1.0.0 = 22 Feb 2008
// 1.0.1 = 26 Feb 2008
// 1.0.2 = 04 Mar 2008
// 1.0.3 = 04 Mar 2008
// 1.0.4 = 11 Apr 2008
// 1.0.5 = 06 Jun 2008
// 1.0.6 = 05 Aug 2008
// 1.0.7 = 28 Sep 2008
// 1.0.8 = 01 Oct 2008
return @"1.0.8";
}
- (NSString *)clientName
{
return [[_clientName retain] autorelease];
}
- (NSString *)clientVersion
{
return [[_clientVersion retain] autorelease];
}
- (NSString *)clientURL
{
return [[_clientURL retain] autorelease];
}
- (NSString *)clientSourceToken
{
return [[_clientSourceToken retain] autorelease];
}
- (void)setClientName:(NSString *)name version:(NSString *)version URL:(NSString *)url token:(NSString *)token;
{
[_clientName release];
_clientName = [name retain];
[_clientVersion release];
_clientVersion = [version retain];
[_clientURL release];
_clientURL = [url retain];
[_clientSourceToken release];
_clientSourceToken = [token retain];
}
- (NSString *)APIDomain
{
return [[_APIDomain retain] autorelease];
}
- (void)setAPIDomain:(NSString *)domain
{
[_APIDomain release];
if (!domain || [domain length] == 0) {
_APIDomain = [TWITTER_DOMAIN retain];
} else {
_APIDomain = [domain retain];
}
}
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
- (NSString *)searchDomain
{
return [[_searchDomain retain] autorelease];
}
- (void)setSearchDomain:(NSString *)domain
{
[_searchDomain release];
if (!domain || [domain length] == 0) {
_searchDomain = [TWITTER_SEARCH_DOMAIN retain];
} else {
_searchDomain = [domain retain];
}
}
#endif
- (BOOL)usesSecureConnection
{
return _secureConnection;
}
- (void)setUsesSecureConnection:(BOOL)flag
{
_secureConnection = flag;
}
- (BOOL)clearsCookies
{
return _clearsCookies;
}
- (void)setClearsCookies:(BOOL)flag
{
_clearsCookies = flag;
}
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
- (MGTwitterEngineDeliveryOptions)deliveryOptions
{
return _deliveryOptions;
}
- (void)setDeliveryOptions:(MGTwitterEngineDeliveryOptions)deliveryOptions
{
_deliveryOptions = deliveryOptions;
}
#endif
#pragma mark Connection methods
- (NSUInteger)numberOfConnections
{
return [_connections count];
}
- (NSArray *)connectionIdentifiers
{
return [_connections allKeys];
}
- (void)closeConnection:(NSString *)connectionIdentifier
{
MGTwitterHTTPURLConnection *connection = [_connections objectForKey:connectionIdentifier];
if (connection) {
[connection cancel];
[_connections removeObjectForKey:connectionIdentifier];
if ([self _isValidDelegateForSelector:@selector(connectionFinished:)])
[_delegate connectionFinished:connectionIdentifier];
}
}
- (void)closeAllConnections
{
[[_connections allValues] makeObjectsPerformSelector:@selector(cancel)];
[_connections removeAllObjects];
}
#pragma mark Utility methods
- (NSDateFormatter *)_HTTPDateFormatter
{
// Returns a formatter for dates in HTTP format (i.e. RFC 822, updated by RFC 1123).
// e.g. "Sun, 06 Nov 1994 08:49:37 GMT"
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
//[dateFormatter setDateFormat:@"%a, %d %b %Y %H:%M:%S GMT"]; // won't work with -init, which uses new (unicode) format behaviour.
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss GMT"];
return dateFormatter;
}
- (NSString *)_queryStringWithBase:(NSString *)base parameters:(NSDictionary *)params prefixed:(BOOL)prefixed
{
// Append base if specified.
NSMutableString *str = [NSMutableString stringWithCapacity:0];
if (base) {
[str appendString:base];
}
// Append each name-value pair.
if (params) {
NSUInteger i;
NSArray *names = [params allKeys];
for (i = 0; i < [names count]; i++) {
if (i == 0 && prefixed) {
[str appendString:@"?"];
} else if (i > 0) {
[str appendString:@"&"];
}
NSString *name = [names objectAtIndex:i];
[str appendString:[NSString stringWithFormat:@"%@=%@",
name, [self _encodeString:[params objectForKey:name]]]];
}
}
return str;
}
- (NSDate *)_HTTPToDate:(NSString *)httpDate
{
NSDateFormatter *dateFormatter = [self _HTTPDateFormatter];
return [dateFormatter dateFromString:httpDate];
}
- (NSString *)_dateToHTTP:(NSDate *)date
{
NSDateFormatter *dateFormatter = [self _HTTPDateFormatter];
return [dateFormatter stringFromDate:date];
}
- (NSString *)_encodeString:(NSString *)string
{
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)string,
NULL,
(CFStringRef)@";/?:@&=$+{}<>,",
kCFStringEncodingUTF8);
return [result autorelease];
}
- (NSString *)getImageAtURL:(NSString *)urlString
{
// This is a method implemented for the convenience of the client,
// allowing asynchronous downloading of users' Twitter profile images.
NSString *encodedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodedUrlString];
if (!url) {
return nil;
}
// Construct an NSMutableURLRequest for the URL and set appropriate request method.
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:URL_REQUEST_TIMEOUT];
// Create a connection using this request, with the default timeout and caching policy,
// and appropriate Twitter request and response types for parsing and error reporting.
MGTwitterHTTPURLConnection *connection;
connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
delegate:self
requestType:MGTwitterImageRequest
responseType:MGTwitterImage];
if (!connection) {
return nil;
} else {
[_connections setObject:connection forKey:[connection identifier]];
[connection release];
}
if ([self _isValidDelegateForSelector:@selector(connectionStarted:)])
[_delegate connectionStarted:[connection identifier]];
return [connection identifier];
}
#pragma mark Request sending methods
#define SET_AUTHORIZATION_IN_HEADER 0
- (NSString *)_sendRequestWithMethod:(NSString *)method
path:(NSString *)path
queryParameters:(NSDictionary *)params
body:(NSString *)body
requestType:(MGTwitterRequestType)requestType
responseType:(MGTwitterResponseType)responseType
{
NSMutableURLRequest *theRequest = [self _baseRequestWithMethod:method
path:path
requestType:requestType
queryParameters:params];
// Set the request body if this is a POST request.
BOOL isPOST = (method && [method isEqualToString:HTTP_POST_METHOD]);
if (isPOST) {
// Set request body, if specified (hopefully so), with 'source' parameter if appropriate.
NSString *finalBody = @"";
if (body) {
finalBody = [finalBody stringByAppendingString:body];
}
// if using OAuth, Twitter already knows your application's name, so don't send it
if (_clientSourceToken && _accessToken == nil) {
finalBody = [finalBody stringByAppendingString:[NSString stringWithFormat:@"%@source=%@",
(body) ? @"&" : @"" ,
_clientSourceToken]];
}
if (finalBody) {
[theRequest setHTTPBody:[finalBody dataUsingEncoding:NSUTF8StringEncoding]];
#if DEBUG
if (YES) {
NSLog(@"MGTwitterEngine: finalBody = %@", finalBody);
}
#endif
}
}
return [self _sendRequest:theRequest withRequestType:requestType responseType:responseType];
}
-(NSString*)_sendRequest:(NSURLRequest *)theRequest withRequestType:(MGTwitterRequestType)requestType responseType:(MGTwitterResponseType)responseType;
{
// Create a connection using this request, with the default timeout and caching policy,
// and appropriate Twitter request and response types for parsing and error reporting.
MGTwitterHTTPURLConnection *connection;
connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
delegate:self
requestType:requestType
responseType:responseType];
if (!connection) {
return nil;
} else {
[_connections setObject:connection forKey:[connection identifier]];
[connection release];
}
if ([self _isValidDelegateForSelector:@selector(connectionStarted:)])
[_delegate connectionStarted:[connection identifier]];
return [connection identifier];
}
- (NSString *)_sendDataRequestWithMethod:(NSString *)method
path:(NSString *)path
queryParameters:(NSDictionary *)params
filePath:(NSString *)filePath
body:(NSString *)body
requestType:(MGTwitterRequestType)requestType
responseType:(MGTwitterResponseType)responseType
{
NSMutableURLRequest *theRequest = [self _baseRequestWithMethod:method
path:path
requestType:requestType
queryParameters:params];
BOOL isPOST = (method && [method isEqualToString:HTTP_POST_METHOD]);
if (isPOST) {
NSString *boundary = @"0xKhTmLbOuNdArY";
NSString *filename = [filePath lastPathComponent];
NSData *imageData = [NSData dataWithContentsOfFile:filePath];
NSString *bodyPrefixString = [NSString stringWithFormat:@"--%@\r\n", boundary];
NSString *bodySuffixString = [NSString stringWithFormat:@"\r\n--%@--\r\n", boundary];
NSString *contentDisposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@\"\r\n", filename];
NSString *contentImageType = [NSString stringWithFormat:@"Content-Type: image/%@\r\n", [filename pathExtension]];
NSString *contentTransfer = @"Content-Transfer-Encoding: binary\r\n\r\n";
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[bodyPrefixString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]];
[postBody appendData:[contentDisposition dataUsingEncoding:NSUTF8StringEncoding ]];
[postBody appendData:[contentImageType dataUsingEncoding:NSUTF8StringEncoding ]];
[postBody appendData:[contentTransfer dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:imageData];
[postBody appendData:[bodySuffixString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]];
[theRequest setHTTPBody:postBody];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary, nil];
[theRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
}
MGTwitterHTTPURLConnection *connection;
connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
delegate:self
requestType:requestType
responseType:responseType];
if (!connection) {
return nil;
} else {
[_connections setObject:connection forKey:[connection identifier]];
[connection release];
}
if ([self _isValidDelegateForSelector:@selector(connectionStarted:)])
[_delegate connectionStarted:[connection identifier]];
return [connection identifier];
}
#pragma mark Base Request
- (NSMutableURLRequest *)_baseRequestWithMethod:(NSString *)method
path:(NSString *)path
requestType:(MGTwitterRequestType)requestType
queryParameters:(NSDictionary *)params
{
NSString *contentType = [params objectForKey:@"Content-Type"];
if(contentType){
params = [params MGTE_dictionaryByRemovingObjectForKey:@"Content-Type"];
}else{
contentType = @"application/x-www-form-urlencoded";
}
// Construct appropriate URL string.
NSString *fullPath = [path stringByAddingPercentEscapesUsingEncoding:NSNonLossyASCIIStringEncoding];
if (params && ![method isEqualToString:HTTP_POST_METHOD]) {
fullPath = [self _queryStringWithBase:fullPath parameters:params prefixed:YES];
}
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
NSString *domain = nil;
NSString *connectionType = nil;
if (requestType == MGTwitterSearchRequest || requestType == MGTwitterSearchCurrentTrendsRequest)
{
domain = _searchDomain;
connectionType = @"http";
}
else
{
domain = _APIDomain;
if (_secureConnection)
{
connectionType = @"https";
}
else
{
connectionType = @"http";
}
}
#else
NSString *domain = _APIDomain;
NSString *connectionType = nil;
if (_secureConnection)
{
connectionType = @"https";
}
else
{
connectionType = @"http";
}
#endif
#if 1 // SET_AUTHORIZATION_IN_HEADER
NSString *urlString = [NSString stringWithFormat:@"%@://%@/%@",
connectionType,
domain, fullPath];
#else
NSString *urlString = [NSString stringWithFormat:@"%@://%@:%@@%@/%@",
connectionType,
[self _encodeString:_username], [self _encodeString:_password],
domain, fullPath];
#endif
NSURL *finalURL = [NSURL URLWithString:urlString];
if (!finalURL) {
return nil;
}
#if DEBUG
if (YES) {
NSLog(@"MGTwitterEngine: finalURL = %@", finalURL);
}
#endif
// Construct an NSMutableURLRequest for the URL and set appropriate request method.
NSMutableURLRequest *theRequest = nil;
if(_accessToken){
theRequest = [[[OAMutableURLRequest alloc] initWithURL:finalURL
consumer:[[[OAConsumer alloc] initWithKey:[self consumerKey]
secret:[self consumerSecret]] autorelease]
token:_accessToken
realm:nil
signatureProvider:nil] autorelease];
[theRequest setCachePolicy:NSURLRequestReloadIgnoringCacheData ];
[theRequest setTimeoutInterval:URL_REQUEST_TIMEOUT];
}else{
theRequest = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:URL_REQUEST_TIMEOUT];
}
if (method) {
[theRequest setHTTPMethod:method];
}
[theRequest setHTTPShouldHandleCookies:NO];
// Set headers for client information, for tracking purposes at Twitter.
[theRequest setValue:_clientName forHTTPHeaderField:@"X-Twitter-Client"];
[theRequest setValue:_clientVersion forHTTPHeaderField:@"X-Twitter-Client-Version"];
[theRequest setValue:_clientURL forHTTPHeaderField:@"X-Twitter-Client-URL"];
[theRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
#if SET_AUTHORIZATION_IN_HEADER
if ([self username] && [self password]) {
// Set header for HTTP Basic authentication explicitly, to avoid problems with proxies and other intermediaries
NSString *authStr = [NSString stringWithFormat:@"%@:%@", [self username], [self password]];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];
[theRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
}
#endif
return theRequest;
}
#pragma mark Parsing methods
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
- (void)_parseDataForConnection:(MGTwitterHTTPURLConnection *)connection
{
NSData *jsonData = [[[connection data] copy] autorelease];
NSString *identifier = [[[connection identifier] copy] autorelease];
MGTwitterRequestType requestType = [connection requestType];
MGTwitterResponseType responseType = [connection responseType];
NSURL *URL = [connection URL];
#if DEBUG
if (NO) {
NSLog(@"MGTwitterEngine: jsonData = %@ from %@", [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease], URL);
}
#endif
#if YAJL_AVAILABLE
switch (responseType) {
case MGTwitterStatuses:
case MGTwitterStatus:
[MGTwitterStatusesYAJLParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
case MGTwitterUsers:
case MGTwitterUser:
[MGTwitterUsersYAJLParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
case MGTwitterDirectMessages:
case MGTwitterDirectMessage:
[MGTwitterMessagesYAJLParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
case MGTwitterMiscellaneous:
[MGTwitterMiscYAJLParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
case MGTwitterSearchResults:
[MGTwitterSearchYAJLParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
case MGTwitterOAuthToken:;
OAToken *token = [[[OAToken alloc] initWithHTTPResponseBody:[[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease]] autorelease];
[self parsingSucceededForRequest:identifier ofResponseType:requestType
withParsedObjects:[NSArray arrayWithObject:token]];
break;
default:
break;
}
#elif TOUCHJSON_AVAILABLE
switch (responseType) {
case MGTwitterOAuthToken:;
OAToken *token = [[[OAToken alloc] initWithHTTPResponseBody:[[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease]] autorelease];
[self parsingSucceededForRequest:identifier ofResponseType:requestType
withParsedObjects:[NSArray arrayWithObject:token]];
break;
default:
[MGTwitterTouchJSONParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
}
#endif
}
#else
- (void)_parseDataForConnection:(MGTwitterHTTPURLConnection *)connection
{
NSString *identifier = [[[connection identifier] copy] autorelease];
NSData *xmlData = [[[connection data] copy] autorelease];
MGTwitterRequestType requestType = [connection requestType];
MGTwitterResponseType responseType = [connection responseType];
#if USE_LIBXML
NSURL *URL = [connection URL];
switch (responseType) {
case MGTwitterStatuses:
case MGTwitterStatus:
[MGTwitterStatusesLibXMLParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL];
break;
case MGTwitterUsers:
case MGTwitterUser:
[MGTwitterUsersLibXMLParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL];
break;
case MGTwitterDirectMessages:
case MGTwitterDirectMessage:
[MGTwitterMessagesLibXMLParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL];
break;
case MGTwitterMiscellaneous:
[MGTwitterMiscLibXMLParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL];
break;
case MGTwitterSocialGraph:
[MGTwitterSocialGraphLibXMLParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL];
break;
case MGTwitterOAuthToken:;
OAToken *token = [[[OAToken alloc] initWithHTTPResponseBody:[[[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding] autorelease]] autorelease];
[self parsingSucceededForRequest:identifier ofResponseType:requestType
withParsedObjects:[NSArray arrayWithObject:token]];
default:
break;
}
#else
// Determine which type of parser to use.
switch (responseType) {
case MGTwitterStatuses:
case MGTwitterStatus:
[MGTwitterStatusesParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
break;
case MGTwitterUsers:
case MGTwitterUser:
[MGTwitterUsersParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
break;
case MGTwitterDirectMessages:
case MGTwitterDirectMessage:
[MGTwitterMessagesParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
break;
case MGTwitterMiscellaneous:
[MGTwitterMiscParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
break;
case MGTwitterUserLists:
NSLog(@"response type: %d", responseType);
[MGTwitterUserListsParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
break;
case MGTwitterSocialGraph:
[MGTwitterSocialGraphParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
case MGTwitterOAuthToken:;
OAToken *token = [[[OAToken alloc] initWithHTTPResponseBody:[[[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding] autorelease]] autorelease];
[self parsingSucceededForRequest:identifier ofResponseType:requestType
withParsedObjects:[NSArray arrayWithObject:token]];
default:
break;
}
#endif
}
#endif
#pragma mark Delegate methods
- (BOOL) _isValidDelegateForSelector:(SEL)selector
{
return ((_delegate != nil) && [_delegate respondsToSelector:selector]);
}
#pragma mark MGTwitterParserDelegate methods
- (void)parsingSucceededForRequest:(NSString *)identifier
ofResponseType:(MGTwitterResponseType)responseType
withParsedObjects:(NSArray *)parsedObjects
{
// Forward appropriate message to _delegate, depending on responseType.
NSLog(@"here at parsingSucceededForRequest");
switch (responseType) {
case MGTwitterStatuses:
case MGTwitterStatus:
if ([self _isValidDelegateForSelector:@selector(statusesReceived:forRequest:)])
[_delegate statusesReceived:parsedObjects forRequest:identifier];
break;
case MGTwitterUsers:
case MGTwitterUser:
if ([self _isValidDelegateForSelector:@selector(userInfoReceived:forRequest:)])
[_delegate userInfoReceived:parsedObjects forRequest:identifier];
break;
case MGTwitterDirectMessages:
case MGTwitterDirectMessage:
if ([self _isValidDelegateForSelector:@selector(directMessagesReceived:forRequest:)])
[_delegate directMessagesReceived:parsedObjects forRequest:identifier];
break;
case MGTwitterMiscellaneous:
if ([self _isValidDelegateForSelector:@selector(miscInfoReceived:forRequest:)])
[_delegate miscInfoReceived:parsedObjects forRequest:identifier];
break;
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
case MGTwitterSearchResults:
if ([self _isValidDelegateForSelector:@selector(searchResultsReceived:forRequest:)])
[_delegate searchResultsReceived:parsedObjects forRequest:identifier];
break;
#endif
case MGTwitterSocialGraph:
if ([self _isValidDelegateForSelector:@selector(socialGraphInfoReceived:forRequest:)])
[_delegate socialGraphInfoReceived: parsedObjects forRequest:identifier];
break;
case MGTwitterUserLists:
if ([self _isValidDelegateForSelector:@selector(userListsReceived:forRequest:)])
[_delegate userListsReceived: parsedObjects forRequest:identifier];
break;
case MGTwitterOAuthTokenRequest:
if ([self _isValidDelegateForSelector:@selector(accessTokenReceived:forRequest:)] && [parsedObjects count] > 0)
[_delegate accessTokenReceived:[parsedObjects objectAtIndex:0]
forRequest:identifier];
break;
default:
break;
}
}
- (void)parsingFailedForRequest:(NSString *)requestIdentifier
ofResponseType:(MGTwitterResponseType)responseType
withError:(NSError *)error
{
if ([self _isValidDelegateForSelector:@selector(requestFailed:withError:)])
[_delegate requestFailed:requestIdentifier withError:error];
}
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
- (void)parsedObject:(NSDictionary *)dictionary forRequest:(NSString *)requestIdentifier
ofResponseType:(MGTwitterResponseType)responseType
{
if ([self _isValidDelegateForSelector:@selector(receivedObject:forRequest:)])
[_delegate receivedObject:dictionary forRequest:requestIdentifier];
}
#endif
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if (_username && _password && [challenge previousFailureCount] == 0 && ![challenge proposedCredential]) {
NSURLCredential *credential = [NSURLCredential credentialWithUser:_username password:_password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
- (void)connection:(MGTwitterHTTPURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it has enough information to create the NSURLResponse.
// it can be called multiple times, for example in the case of a redirect, so each time we reset the data.
[connection resetDataLength];
// Get response code.
NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
[connection setResponse:resp];
NSInteger statusCode = [resp statusCode];
if (statusCode == 304 || [connection responseType] == MGTwitterGeneric) {
// Not modified, or generic success.
if ([self _isValidDelegateForSelector:@selector(requestSucceeded:)])
[_delegate requestSucceeded:[connection identifier]];
if (statusCode == 304) {
[self parsingSucceededForRequest:[connection identifier]
ofResponseType:[connection responseType]
withParsedObjects:[NSArray array]];
}
// Destroy the connection.
[connection cancel];
NSString *connectionIdentifier = [connection identifier];
[_connections removeObjectForKey:connectionIdentifier];
if ([self _isValidDelegateForSelector:@selector(connectionFinished:)])
[_delegate connectionFinished:connectionIdentifier];
}
#if DEBUG