-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWimSession.m
1927 lines (1547 loc) · 59.2 KB
/
WimSession.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) 2008 AOL LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
Neither the name of the AOL LCC nor the names of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WimSession.h"
#import "WimRequest.h"
#import "ClientLogin.h"
#import "ClientLogin+Private.h"
#import "NSDataAdditions.h"
#import "WimConstants.h"
#import "JSON.h"
#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
#import <CommonCrypto/CommonHMAC.h>
#else
#import "CommonHMAC.h"
#endif
#import "MLog.h"
//#define kUrlFetchTimeout = @"14000"; //14 seconds
//#define kUrlFetchTimeout = @"28000"; //28 seconds
//#define kUrlFetchTimeout = @"480000"; //8 minutes
#define kUrlFetchTimeout 180000 // 3 minutes
const int kHttpFetchTimeout = kUrlFetchTimeout / 1000 + 5;
const int kSessionTimeout = 480; // 8 minutes
WimSession* gDefaultSession = nil;
@interface WimSession (PRIVATEAPI)
- (void)setConnectionState:(ConnectionState)newConnectionState;
- (void)connectionAuthenticate;
- (void)requestTokenForName:(NSString*)screenName withPassword:(NSString*)password;
- (void)startSession;
- (void)endSession;
- (void)onAimPresenceResponse:(NSNotification *)notification;
- (void)setBuddyList:(NSDictionary *)buddyList;
- (void)fetchEvents;
- (BOOL)validateBuddyList;
- (void)onWimEventFetchEvents:(WimRequest *)wimRequest withError:(NSError *)error;
- (void)replyToProposal:(NSDictionary*)invitation withResponse:(NSString*)response; // isAutoResponse:(BOOL)isAutoResponse
@end
NSDictionary *WimSession_OnlineStateInts;
NSDictionary *WimSession_OnlineStateStrings;
@implementation WimSession
@synthesize statusMessage = _statusMessage;
@synthesize awayMessage = _awayMessage;
@synthesize clientOrnament = _clientOrnament;
- (int)nextRequestId
{
return _WimRequestId++;
}
+ (WimSession*)defaultSession
{
if (gDefaultSession == nil)
{
MLog(@"Initializing a new global WimSession");
gDefaultSession = [[WimSession alloc] init];
}
return gDefaultSession;
}
extern void IMLog(NSString *,...);
+ (void)initialize
{
WimSession_OnlineStateInts = [[NSDictionary dictionaryWithObjectsAndKeys:
@"1" , @"online",
@"2", @"invisible",
@"3", @"notFound",
@"4", @"idle",
@"5" , @"away",
@"6", @"mobile",
@"7", @"offline",
nil ] retain];
WimSession_OnlineStateStrings = [[NSDictionary dictionaryWithObjectsAndKeys:
@"online", @"1",
@"invisible", @"2",
@"notFound", @"3",
@"idle", @"4",
@"away", @"5",
@"mobile", @"6",
@"offline", @"7",
nil ] retain];
}
- (id)init
{
if (self = [super init])
{
}
return self;
}
- (id)initWithCoder:(NSCoder *)coder
{
self = [super init];
_userName = [[coder decodeObjectForKey:@"userName"] retain];
_sessionKey = [[coder decodeObjectForKey:@"sessionKey"] retain];
_sessionId = [[coder decodeObjectForKey:@"sessionId"] retain];
_authToken = [[coder decodeObjectForKey:@"authToken"] retain];
_tokenExpiration = [[coder decodeObjectForKey:@"tokenExpiration"] retain];
_buddyList = [[coder decodeObjectForKey:@"buddyList"] retain];
_passwordHash = [[coder decodeObjectForKey:@"passwordHash"] intValue];
_fetchUrl = [[coder decodeObjectForKey:@"reconnectUrl"] retain];
_WimRequestId = [[coder decodeObjectForKey:@"wimRequestId"] intValue];
_myInfo = [[coder decodeObjectForKey:@"myInfo"] retain];
_statusMessage = [[coder decodeObjectForKey:@"lastStatusMessage"] retain];
_awayMessage = [[coder decodeObjectForKey:@"lastAwayMessage"] retain];
_clockSkew = [[coder decodeObjectForKey:@"clockSkew"] doubleValue];
if ([self validateBuddyList] == NO)
{
[_buddyList release];
_buddyList = nil;
[_sessionKey release];
_sessionKey = nil;
[_fetchUrl release];
_fetchUrl = nil;
}
// this seems wrong - perhaps defaultSession should be a property allowing the caller to specify which object is the defaultSession?
if (gDefaultSession != self)
{
//[self retain];
[gDefaultSession autorelease];
MLog(@"WimSession - old gDefaultSession: %d", [gDefaultSession retainCount]);
MLog(@"WimSession - new gDefaultSession: %d", [self retainCount]);
MLog(@"WimSession - replacing global with new WimSession object");
gDefaultSession = self;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:_userName forKey:@"userName"];
[coder encodeObject:_sessionKey forKey:@"sessionKey"];
[coder encodeObject:_sessionId forKey:@"sessionId"];
[coder encodeObject:_authToken forKey:@"authToken"];
[coder encodeObject:_tokenExpiration forKey:@"tokenExpiration"];
[coder encodeObject:_buddyList forKey:@"buddyList"];
[coder encodeObject:[NSNumber numberWithInt:_passwordHash] forKey:@"passwordHash"];
[coder encodeObject:_fetchUrl forKey:@"reconnectUrl"];
[coder encodeObject:[NSNumber numberWithInt:_WimRequestId] forKey:@"wimRequestId"];
[coder encodeObject:_myInfo forKey:@"myInfo"];
[coder encodeObject:_statusMessage forKey:@"lastStatusMessage"];
[coder encodeObject:_awayMessage forKey:@"lastAwayMessage"];
[coder encodeObject:[NSNumber numberWithDouble:_clockSkew] forKey:@"clockSkew"];
}
- (void)dealloc
{
MLog(@"WimSession deallocing...");
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_wimFetchRequest setDelegate:nil];
[_fetchUrl release];
[_userName release];
[_password release];
[_sessionId release];
[_authToken release];
[_tokenExpiration release];
[_clientLogin release];
[_devID release];
[_clientVersion release];
[_clientName release];
[_capabilityUUIDs release];
[_clientOrnament release];
if (self == gDefaultSession)
gDefaultSession = nil;
[super dealloc];
}
#pragma mark WimSession core methods
// AIM Clients are required to use a application/developmenent ID - request yours at developer.aim.com
- (NSString *)devID
{
return _devID;
}
- (void)setDevID:(NSString *)aDevID
{
aDevID = [aDevID copy];
[_devID release];
_devID = aDevID;
}
- (NSString *)clientName
{
return _clientName;
}
- (void)setClientName:(NSString *)aClientName
{
aClientName = [aClientName copy];
[_clientName release];
_clientName = aClientName;
}
- (NSString *)clientVersion
{
return _clientVersion;
}
- (void)setClientVersion:(NSString *)aClientVersion
{
aClientVersion = [aClientVersion copy];
[_clientVersion release];
_clientVersion = aClientVersion;
}
- (NSSet*)capabilityUUIDs
{
return _capabilityUUIDs;
}
- (void)setCapabilityUUIDs:(NSSet *)aCapabilitySet
{
// ++++ validate input in debug builds
[aCapabilitySet retain];
[_capabilityUUIDs release];
_capabilityUUIDs = aCapabilitySet;
}
- (BOOL)online
{
// if internal state is reconnecting or connected
return ![self offline];
}
- (BOOL)offline
{
// if internal state is logged out, authenticating or connecting
switch (connectionState) {
case ConnectionState_Offline:
return YES;
case ConnectionState_Authenticating:
return YES;
case ConnectionState_Connecting:
return YES;
case ConnectionState_Reconnecting:
return NO;
case ConnectionState_Connected:
return NO;
default:
MLog(@"Connection reached unknown state");
return NO;
}
}
- (ConnectionState)connectionState
{
return connectionState;
}
- (BOOL)connected
{
return self.connectionState > ConnectionState_Reconnecting;
}
- (BOOL)reconnecting
{
return self.connectionState == ConnectionState_Reconnecting;
}
- (void)connect
{
if (self.connectionState == ConnectionState_Offline)
[self setConnectionState:ConnectionState_Authenticating];
}
- (void)signOff
{
// reset the connection such that we'll restart the ConnectionState state machine
[self resetSession];
[self endSession];
}
- (void)setConnectionState:(ConnectionState)aConnectionState
{
ConnectionState previousState = connectionState;
connectionState = aConnectionState;
switch (connectionState) {
case ConnectionState_Offline:
_sessionAttempt = 0;
[[NSNotificationCenter defaultCenter] postNotificationName:kWimClientConnectionStateChange object:self];
break;
case ConnectionState_Authenticating:
// Signing on...
_sessionAttempt = 0;
[self connectionAuthenticate];
break;
case ConnectionState_Connecting:
case ConnectionState_Reconnecting:
if (_fetchUrl==nil)
{
connectionState = ConnectionState_Connecting;
[[NSNotificationCenter defaultCenter] postNotificationName:kWimClientConnectionStateChange object:self];
// Connecting...
_sessionAttempt = 0;
[self startSession];
}
else
{
// Reconnecting...
connectionState = ConnectionState_Reconnecting;
[[NSNotificationCenter defaultCenter] postNotificationName:kWimClientConnectionStateChange object:self];
[self fetchEvents];
}
break;
case ConnectionState_Connected:
if (previousState != ConnectionState_Connected)
[[NSNotificationCenter defaultCenter] postNotificationName:kWimClientConnectionStateChange object:self];
break;
default:
MLog(@"continueConnection reached unknown state");
break;
}
}
- (void)connectionAuthenticate
{
NSString *user = [[self userName] lowercaseString];
NSString *aimId = [[[self myInfo] aimId] lowercaseString];
BOOL validAimId = NO;
BOOL validPassword = NO;
BOOL validToken = NO;
if ([user isEqualToString:aimId] == YES)
{
validAimId = YES;
}
if ([[self password] hash] == _passwordHash)
{
validPassword = YES ;
}
if (_tokenExpiration && [[NSDate date] earlierDate:_tokenExpiration] && _authToken && _sessionKey)
{
validToken = YES;
}
if (validAimId && validPassword && validToken)
{
[self setConnectionState:ConnectionState_Connecting];
}
else
{
[_clientLogin release];
_clientLogin = [[ClientLogin alloc] init];
[_clientLogin setDelegate:self];
if ([_userName length])
{
if ([_password length])
{
[[NSNotificationCenter defaultCenter] postNotificationName:kWimClientConnectionStateChange object:self];
[self requestTokenForName:_userName withPassword:_password];
}
else
{
if ([_delegate respondsToSelector:@selector(wimSessionRequiresPassword:)])
[_delegate performSelector:@selector(wimSessionRequiresPassword:) withObject:self];
}
}
else
{
[self setConnectionState:ConnectionState_Offline];
}
}
}
- (void)answerChallenge:(NSString *)challengeAnswer
{
if ( [_userName isEqualToString:[_clientLogin screenName]] == NO || [_password length] == 0)
{
[_password autorelease];
_password = [challengeAnswer copy];
[self setConnectionState:ConnectionState_Authenticating];
}
else
{
[_clientLogin answerChallenge:challengeAnswer];
}
}
- (void)requestPresenceForAimId:(NSString*)aimId
{
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventPresenceResponse:withError:)];
NSString* urlString = [NSString stringWithFormat:kUrlPresenceRequest, kAPIBaseURL, [[self devID] urlencode], [aimId urlencode]];
NSURL *url = [NSURL URLWithString:urlString];
[wimRequest setUserData:self];
[wimRequest requestURL:url];
}
- (void)requestBuddyInfoForAimId:(NSString*)aimId
{
NSString *kUrlGetBuddyInfo = @"%@aim/getHostBuddyInfo?f=html&t=%@&aimsid=%@"; // requires: kAPIBaseURL, aimId, aimSid
NSString* urlString = [NSString stringWithFormat: kUrlGetBuddyInfo, kAPIBaseURL, [aimId urlencode], _sessionId];
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventGetHostBuddyInfoResponse:withError:)];
MLog (@"fetching %@", urlString);
NSArray *userData = [NSArray arrayWithObjects:aimId, nil];
[wimRequest setUserData:userData];
[wimRequest requestURL:url];
}
- (void)addBuddy:(NSString *)aimId toGroup:(NSString *)groupName thenInvoke:(NSInvocation *)aInvocation
{
// looks like we need to do some additional encoding to handle SMS based aimId's
//NSString *encodedAimId = [aimId urlencode];
NSString *kUrlAddBuddy = @"%@buddylist/addBuddy?f=json&k=%@&a=%@&aimsid=%@&r=%d&buddy=%@&group=%@"; // requires: kAPIBaseURL, key, authtoken, aimSid, requestid, newBuddy, groupName
NSString* urlString = [NSString stringWithFormat: kUrlAddBuddy, kAPIBaseURL, [self devID], _authToken, _sessionId, [self nextRequestId],
[aimId urlencode], [groupName urlencode]];
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventAddBuddyResponse:withError:)];
MLog (@"fetching %@", urlString);
if (aInvocation)
{
NSDictionary *userDictionary = [NSDictionary dictionaryWithObject:aInvocation forKey:@"delayedInvocation"];
[wimRequest setUserData:userDictionary];
}
[wimRequest requestURL:url];
}
// Add/Remove Buddies
- (void)addBuddy:(NSString *)aimId withFriendlyName:(NSString *)friendlyName toGroup:(NSString *)groupName
{
NSInvocation *anInvocation = nil;
if (friendlyName)
{
SEL selector = @selector(setFriendlyName:toAimId:);
anInvocation = [NSInvocation invocationWithMethodSignature:[WimSession instanceMethodSignatureForSelector:selector]];
[anInvocation setSelector:selector];
[anInvocation retainArguments];
[anInvocation setTarget:self];
[anInvocation setArgument:&friendlyName atIndex:2];
[anInvocation setArgument:&aimId atIndex:3];
}
[self addBuddy:aimId toGroup:groupName thenInvoke:anInvocation];
}
- (void)removeBuddy:(NSString *)aimId fromGroup:(NSString *)groupName
{
// looks like we need to do some additional encoding to handle SMS based aimId's
//NSString *encodedAimId = [aimId urlencode];
NSString *kUrlRemoveBuddy = @"%@buddylist/removeBuddy?f=json&k=%@&a=%@&aimsid=%@&r=%d&buddy=%@&group=%@"; // requires: kAPIBaseURL, key, authtoken, aimSid, requestid, newBuddy, groupName
NSString* urlString = [NSString stringWithFormat: kUrlRemoveBuddy, kAPIBaseURL, [self devID], _authToken, _sessionId, [self nextRequestId],
[aimId urlencode], [groupName urlencode]];
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventRemoveBuddyResponse:withError:)];
MLog (@"fetching %@", urlString);
[wimRequest requestURL:url];
}
- (void)moveBuddy:(NSString *)aimId fromGroup:(NSString *)oldGroup toGroup:(NSString *)newGroup
{
if (oldGroup && newGroup)
{
SEL selector = @selector(removeBuddy:fromGroup:);
NSInvocation *anInvocation;
anInvocation = [NSInvocation invocationWithMethodSignature:[WimSession instanceMethodSignatureForSelector:selector]];
[anInvocation setSelector:selector];
[anInvocation retainArguments];
[anInvocation setTarget:self];
[anInvocation setArgument:&aimId atIndex:2];
[anInvocation setArgument:&oldGroup atIndex:3];
[self addBuddy:aimId toGroup:newGroup thenInvoke:anInvocation];
}
}
- (void)setFriendlyName:(NSString*)friendlyName toAimId:(NSString*)aimId
{
NSString* urlString = [NSString stringWithFormat: kUrlSetBuddyAttribute, kAPIBaseURL, [self devID], _authToken, _sessionId, [self nextRequestId],
[aimId urlencode], [friendlyName urlencode]];
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventSetBuddyAttributeResponse:withError:)];
MLog (@"fetching %@", urlString);
[wimRequest setUserData:aimId];
[wimRequest requestURL:url];
}
- (void)moveGroup:(NSString *)groupName beforeGroup:(NSString *)beforeGroup
{
NSString* urlString;
if (beforeGroup)
{
NSString *kUrlMoveGroup = @"%@buddylist/moveGroup?f=json&k=%@&a=%@&aimsid=%@&r=%d&group=%@&beforeGroup=%@"; // requires: kAPIBaseURL, key, authtoken, aimSid, requestid, groupName, beforeGroup
urlString = [NSString stringWithFormat: kUrlMoveGroup, kAPIBaseURL, [self devID], _authToken, _sessionId, [self nextRequestId],
[groupName urlencode], [beforeGroup urlencode]];
}
else
{
NSString *kUrlMoveGroup = @"%@buddylist/moveGroup?f=json&k=%@&a=%@&aimsid=%@&r=%d&group=%@"; // requires: kAPIBaseURL, key, authtoken, aimSid, requestid, groupName, beforeGroup
urlString = [NSString stringWithFormat: kUrlMoveGroup, kAPIBaseURL, [self devID], _authToken, _sessionId, [self nextRequestId],
[groupName urlencode]];
}
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventMoveGroupResponse:withError:)];
MLog (@"fetching %@", urlString);
[wimRequest requestURL:url];
}
- (void)removeGroup:(NSString *)group
{
NSString* urlString = [NSString stringWithFormat: kUrlRemoveGroup, kAPIBaseURL, [self devID], _authToken, _sessionId, [self nextRequestId],
[group urlencode]];
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventRemoveGroupResponse:withError:)];
MLog (@"fetching %@", urlString);
[wimRequest setUserData:group];
[wimRequest requestURL:url];
}
- (void)sendInstantMessage:(NSString*)message toAimId:(NSString*)aimId
{
[self sendInstantMessage:message toAimId:aimId isAutoResponse:NO sendOfflineIfNeeded:NO];
}
- (void)sendInstantMessage:(NSString*)message toAimId:(NSString*)aimId isAutoResponse:(BOOL)isAutoResponse sendOfflineIfNeeded:(BOOL)sendOfflineIfNeeded
{
// looks like we need to do some additional encoding to handle SMS based aimId's
//NSString *encodedAimId = [aimId urlencode];
// looks like we need to do some additional encoding to handle +
NSString* urlString = [NSString stringWithFormat: kUrlSendIMRequest, kAPIBaseURL, [self devID], _authToken, _sessionId, [self nextRequestId],
[[NSString stringWithFormat:@"<div>%@</div>", [NSString encodeHTMLEntities:message]] urlencode], [aimId urlencode], (isAutoResponse ? @"1" : @"0"),(sendOfflineIfNeeded ? @"1" : @"0")];
NSURL *url = [NSURL URLWithString:urlString];
if (!url) { MLog(@"sendInstantMessage created invalid URL"); return;}
//http://api.oscar.aol.com/im/sendIM?f=json&k=MYKEY&c=callback&aimsid=AIMSID&msg=Hi&t=ChattingChuck
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventIMSentResponse:withError:)];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
message, @"message",
aimId, @"aimId",
[NSNumber numberWithBool:isAutoResponse], @"autoresponse",
[NSNumber numberWithBool:sendOfflineIfNeeded], @"sendOffline", nil];
MLog (@"fetching %@", urlString);
[wimRequest setUserData:dictionary];
[wimRequest requestURL:url];
}
- (void)acceptProposal:(NSDictionary*)invitation // isAutoResponse:(BOOL)isAutoResponse
{
[self replyToProposal:invitation withResponse:@"accept"];
}
- (void)denyProposal:(NSDictionary*)invitation // isAutoResponse:(BOOL)isAutoResponse
{
[self replyToProposal:invitation withResponse:@"deny"];
}
- (void)replyToProposal:(NSDictionary*)invitation withResponse:(NSString*)response // isAutoResponse:(BOOL)isAutoResponse
{
// NSString* kUrlSendDataIM = @"%@im/sendDataIM?f=json&k=%@&a=%@&aimsid=%@&r=%d&&t=%@&cap=%@&type=%@&data=%@";
// requires: kAPIBaseURL, key, authtoken, aimSid,requestid,target,capability,type,data
NSMutableString* urlString = [NSMutableString stringWithFormat: kUrlSendDataIM, kAPIBaseURL, [self devID], _authToken, _sessionId, [self nextRequestId],
[invitation valueForKeyPath:@"eventData.source.aimId"], // ++++ need to re-encode target screenname?
[invitation valueForKeyPath:@"eventData.dataCapability"],
response,
@"x"]; // the data argument is required, although I don't think it is useful here
// These are appended because I'm not yet sure that they are always required.
// if anything is always required, it should be added to kUrlSendDataIM
[urlString appendFormat:@"&cookie=%@", [invitation valueForKeyPath:@"eventData.cookie"]];
[urlString appendFormat:@"&sequenceNum=%@", [invitation valueForKeyPath:@"eventData.sequenceNum"]];
NSURL *url = [NSURL URLWithString:urlString];
if (!url) { MLog(@"replyToProposal created invalid URL"); return;}
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventProposalReplySentResponse:withError:)];
// I don't think we need to create a dictionary, then
// [wimRequest setUserData:dictionary];
MLog (@"fetching %@", urlString);
[wimRequest requestURL:url];
}
- (void)setState:(OnlineState)onlineState withMessage:(NSString *)message
{
//http://api.oscar.aol.com/presence/setState?f=json&k=MYKEY&c=callback&aimsid=AIMSID&view=away&away=Gone
NSString *stateString = [WimSession_OnlineStateStrings valueForKey:[NSString stringWithFormat:@"%d", onlineState]];
NSString *kUrlSetState = @"%@presence/setState?f=json&aimsid=%@&r=%d&view=%@"; // requires kAPIBaseURL, authtoken, requestid, state
NSMutableString* urlString = [NSMutableString stringWithString:[NSString stringWithFormat: kUrlSetState, kAPIBaseURL, _sessionId, [self nextRequestId], stateString]];
if (onlineState == OnlineState_away && message)
{
[urlString appendFormat:@"&away=%@", [message urlencode]];
}
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventSetStateResponse:withError:)];
MLog (@"fetching %@", urlString);
[wimRequest requestURL:url];
}
- (void)setStatus:(NSString *)message
{
NSMutableString *queryString = [[[NSMutableString alloc] init] autorelease];
[queryString appendValue:@"json" forName:@"f"];
[queryString appendValue:[NSString stringWithFormat:@"%d", [self nextRequestId]] forName:@"r"];
[queryString appendValue:_sessionId forName:@"aimsid"];
if (message)
{
// [queryString appendValue:message forName:@"statusMsg"];
// [queryString appendFormat:@"&statusMsg=%@", [[message stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] urlencode]];
[queryString appendFormat:@"&statusMsg=%@", [message urlencode]];
}
else
{
[queryString appendString:@"&statusMsg="];
}
NSString *urlString = [NSMutableString stringWithFormat:@"%@presence/setStatus?%@", kAPIBaseURL, queryString];
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventSetStatusResponse:withError:)];
MLog (@"fetching %@", urlString);
[wimRequest requestURL:url];
}
- (void)setProfile:(NSString *)message
{
NSMutableString *queryString = [[[NSMutableString alloc] init] autorelease];
[queryString appendValue:@"json" forName:@"f"];
[queryString appendValue:[NSString stringWithFormat:@"%d", [self nextRequestId]] forName:@"r"];
[queryString appendValue:_sessionId forName:@"aimsid"];
//[queryString appendFormat:@"&profile=%@", [message urlencode]];
[queryString appendValue:message forName:@"profile"];
NSString *urlString = [NSMutableString stringWithFormat:@"%@presence/setProfile?%@", kAPIBaseURL, queryString];
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventSetProfileResponse:withError:)];
MLog (@"fetching %@", urlString);
[wimRequest requestURL:url];
}
- (void)setLargeBuddyIcon:(NSData*)iconData
{
// requires: kAPIBaseURL, key, authtoken, aimSid, requestid, expression type
NSString* urlString = [NSString stringWithFormat: kUrlUploadExpression, kAPIBaseURL, [self devID], _authToken, _sessionId, [self nextRequestId],
@"buddyIcon"];
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventSetLargeBuddyIconResponse:withError:)];
MLog (@"posting %@", urlString);
[wimRequest requestURL:url withData:iconData];
}
- (void)setExpresssion:(NSString *)expressionId
{
NSString *kUrlSetExpression = @"%@expressions/set?f=json&k=%@&a=%@&aimsid=%@&r=%d&type=%@&id=%@";
// requires: kAPIBaseURL, key, authtoken, aimSid, requestid, expression type, expression id
NSString* urlString = [NSString stringWithFormat: kUrlSetExpression, kAPIBaseURL, [self devID], _authToken, _sessionId, [self nextRequestId],
@"buddyIcon", expressionId];
NSURL *url = [NSURL URLWithString:urlString];
WimRequest *wimRequest = [WimRequest wimRequest];
[wimRequest setDelegate:self];
[wimRequest setAction:@selector(onWimEventSetExpressionResponse:withError:)];
MLog (@"posting %@", urlString);
[wimRequest requestURL:url];
}
#pragma mark ClientLogin Delegate
- (void) clientLoginRequiresChallenge:(ClientLogin *)aClientLogin
{
// delegate UI handling login challenge - delegate should relogin after providing answer to challenge
int code = [[aClientLogin statusDetailCode] intValue];
switch (code)
{
case 3011: // password challenge
[_password autorelease];
_password = @"";
if ([_delegate respondsToSelector:@selector(wimSessionRequiresPassword:)])
[_delegate performSelector:@selector(wimSessionRequiresPassword:) withObject:self];
break;
case 3012: // securid challenge
case 3013: // securid seconde challenge
if ([_delegate respondsToSelector:@selector(wimSessionRequiresChallenge:)])
[_delegate performSelector:@selector(wimSessionRequiresChallenge:) withObject:self];
break;
case 3015: // captcha challenge
if ([_delegate respondsToSelector:@selector(wimSessionRequiresCaptcha:url:)])
{
NSString *captchaURL = [NSString stringWithFormat:@"%@?devId=%@&f=image&context=%@", [aClientLogin challengeURL], [self devID], [aClientLogin challengeContext]];
NSURL *url = [NSURL URLWithString:captchaURL];
[_delegate performSelector:@selector(wimSessionRequiresCaptcha:url:) withObject:self withObject:url];
}
break;
default:
MLog(@"clientLoginRequiresChallenge unsupported secondary challenge");
break;
}
}
- (void) clientLoginComplete:(ClientLogin *)aClientLogin
{
MLog(@"onAimLoginEventTokenGranted");
_passwordHash = [[self password] hash];
[_sessionKey release];
_sessionKey = [[aClientLogin sessionKey] retain];
[_authToken release];
_authToken = [[aClientLogin tokenStr] retain];
NSTimeInterval seconds = [[aClientLogin expiresIn] intValue];
NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:seconds];
[_tokenExpiration release];
_tokenExpiration = [expirationDate retain];
_clockSkew = [aClientLogin clockSkew];
// we are done with the client login
[_clientLogin release];
_clientLogin = nil;
[self setConnectionState:ConnectionState_Connecting];
}
- (void) clientLoginFailed:(ClientLogin *)aClientLogin
{
MLog(@"onAimLoginEventTokenFailure");
// if login is failing - don't use cached credentials
[_tokenExpiration release];
_tokenExpiration = nil;
[_authToken release];
_authToken = nil;
[_sessionKey release];
_sessionKey = nil;
// we are done with the client login
[_clientLogin release];
_clientLogin = nil;
[self setConnectionState:ConnectionState_Offline];
}
- (BOOL)validateBuddyList
{
NSArray *buddyList = [_buddyList valueForKey:@"groups"];
NSEnumerator* buddyListGroups = [buddyList objectEnumerator];
NSArray* buddyGroup;
while ((buddyGroup = [buddyListGroups nextObject]))
{
NSEnumerator *buddies = [[buddyGroup valueForKey:@"buddies"] objectEnumerator];
NSMutableDictionary *buddy;
//NSString *groupName = [buddyGroup valueForKey:@"name"];
while (buddy = [buddies nextObject])
{
NSString *aimId = [buddy aimId];
if (aimId == nil)
{
MLog(@"buddy list validation failed from disk %@", buddy);
return NO;
}
}
}
return YES;
}
- (void)buddyListArrived
{
MLog(@"buddyListArrived");
NSArray *buddyList = [_buddyList valueForKey:@"groups"];
NSEnumerator* buddyListGroups = [buddyList objectEnumerator];
NSArray* buddyGroup;
while ((buddyGroup = [buddyListGroups nextObject]))
{
NSEnumerator *buddies = [[buddyGroup valueForKey:@"buddies"] objectEnumerator];
NSMutableDictionary *buddy;
NSString *groupName = [buddyGroup valueForKey:@"name"];
while (buddy = [buddies nextObject])
{
[buddy setObject:groupName forKey:@"_group"];
}
}
[_delegate wimSession:self receivedBuddyList:_buddyList];
}
- (void)updateBuddyListWithBuddy:(NSDictionary*)newBuddyInfo
{
MLog(@"updateBuddyListwithBuddy: %@", newBuddyInfo );
NSArray *buddyList = [_buddyList valueForKey:@"groups"];
NSEnumerator* buddyListGroups = [buddyList objectEnumerator];
NSArray* buddyGroups;
while ((buddyGroups = [buddyListGroups nextObject]))
{
NSEnumerator *buddies = [[buddyGroups valueForKey:@"buddies"] objectEnumerator];
NSMutableDictionary *buddy;
while (buddy = [buddies nextObject])
{
// fire presence events for existing UI - allowing prexisting UI to update state
if ( [buddy isEqualToBuddy:newBuddyInfo] )
{
[buddy updateBuddy:newBuddyInfo];
[_delegate wimSession:self receivedPresenceEvent:buddy];
}
}
}
}
#pragma mark EventParser
- (void)parseEvents:(NSArray*)aEvents
{
NSEnumerator* enumerator = [aEvents objectEnumerator];
NSArray* event;
while ((event = [enumerator nextObject]))
{
// should eventdata be reparsed as Dictionary?
NSString* type = [event stringValueForKeyPath:@"type"];
if ([type isEqualToString:@"myInfo"])
{
NSMutableDictionary *buddy = [event valueForKey:@"eventData"];
if (![buddy isKindOfClass:[NSMutableDictionary class]] )
{
buddy = [buddy mutableCopy];
}
MLog(@"MyInfo: %@", buddy);
if ([[buddy valueForKey:@"invisible"] intValue] == 0 && ![[_myInfo state] isEqualToString:@"invisible"]) // reset state after invisibility turns off remotely
{
[buddy setValue:[_myInfo state] forKey:@"state"];
if ([buddy awayMsg])
{
[_awayMessage release];
_awayMessage = [[buddy awayMsg] copy]; //awayMsg contains xhtml
}
else
{
[_statusMessage release];
_statusMessage = [[NSString decodeHTMLEntities:[buddy statusMsg]] retain];
}
}
[_myInfo release];
_myInfo = [buddy retain];
[_delegate wimSession:self receivedMyInfoEvent:buddy];
}
else if ([type isEqualToString:@"presence"])
{
NSDictionary *buddy = [event valueForKey:@"eventData"];
[self updateBuddyListWithBuddy:buddy]; // Update the data to keep it in sync...
}
else if ([type isEqualToString:@"buddylist"])