forked from tinycode/xmppframework
/
XMPPClient.m
1008 lines (822 loc) · 24.9 KB
/
XMPPClient.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
#import "XMPPClient.h"
#import "XMPPStream.h"
#import "XMPPJID.h"
#import "XMPPUser.h"
#import "XMPPResource.h"
#import "XMPPIQ.h"
#import "XMPPMessage.h"
#import "XMPPPresence.h"
#import "NSXMLElementAdditions.h"
#import "MulticastDelegate.h"
#import "SCNotificationManager.h"
enum XMPPClientFlags
{
kUsesOldStyleSSL = 1 << 0, // If set, TLS is established prior to any communication (no StartTLS)
kAutoLogin = 1 << 1, // If set, client automatically attempts login after connection is established
kAllowsPlaintextAuth = 1 << 2, // If set, client allows plaintext authentication
kAutoRoster = 1 << 3, // If set, client automatically request roster after authentication
kAutoPresence = 1 << 4, // If set, client automatically becaomes available after authentication
kAutoReconnect = 1 << 5, // If set, client automatically attempts to reconnect after a disconnection
kShouldReconnect = 1 << 6, // If set, disconnection was accidental, and autoReconnect may be used
kHasRoster = 1 << 7, // If set, client has received the roster
};
@interface XMPPClient (PrivateAPI)
- (void)onConnecting;
- (void)onDidConnect;
- (void)onDidDisconnect;
- (void)onDidRegister;
- (void)onDidNotRegister:(NSXMLElement *)error;
- (void)onDidAuthenticate;
- (void)onDidNotAuthenticate:(NSXMLElement *)error;
- (void)onDidUpdateRoster;
- (void)onDidReceiveBuddyRequest:(XMPPJID *)jid;
- (void)onDidReceiveIQ:(XMPPIQ *)iq;
- (void)onDidReceiveMessage:(XMPPMessage *)message;
@end
@implementation XMPPClient
- (id)init
{
if(self = [super init])
{
multicastDelegate = [[MulticastDelegate alloc] init];
priority = 1;
flags = 0;
[self setAutoLogin:YES];
[self setAllowsPlaintextAuth:YES];
[self setAutoPresence:YES];
[self setAutoRoster:YES];
[self setAutoReconnect:YES];
xmppStream = [[XMPPStream alloc] initWithDelegate:self];
roster = [[NSMutableDictionary alloc] initWithCapacity:10];
earlyPresenceElements = [[NSMutableArray alloc] initWithCapacity:2];
scNotificationManager = [[SCNotificationManager alloc] init];
// Register for network notifications from system configuration
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(networkStatusDidChange:)
name:@"State:/Network/Global/IPv4"
object:scNotificationManager];
}
return self;
}
- (void)dealloc
{
[multicastDelegate release];
[domain release];
[myJID release];
[password release];
[xmppStream setDelegate:nil];
[xmppStream disconnect];
[xmppStream release];
[streamError release];
[roster release];
[myUser release];
[earlyPresenceElements release];
[scNotificationManager release];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)addDelegate:(id)delegate
{
[multicastDelegate addDelegate:delegate];
}
- (void)removeDelegate:(id)delegate
{
[multicastDelegate removeDelegate:delegate];
}
- (NSString *)domain
{
return domain;
}
- (void)setDomain:(NSString *)newDomain
{
if(![domain isEqual:newDomain])
{
[domain release];
domain = [newDomain copy];
}
}
- (UInt16)port
{
return port;
}
- (void)setPort:(UInt16)newPort
{
port = newPort;
}
- (BOOL)usesOldStyleSSL
{
return (flags & kUsesOldStyleSSL);
}
- (void)setUsesOldStyleSSL:(BOOL)flag
{
if(flag)
flags |= kUsesOldStyleSSL;
else
flags &= ~kUsesOldStyleSSL;
}
- (XMPPJID *)myJID
{
return myJID;
}
- (void)setMyJID:(XMPPJID *)jid
{
if(![myJID isEqual:jid])
{
[myJID release];
myJID = [jid retain];
}
}
- (NSString *)password
{
return password;
}
- (void)setPassword:(NSString *)newPassword
{
if(![password isEqual:newPassword])
{
[password release];
password = [newPassword copy];
}
}
- (int)priority
{
return priority;
}
- (void)setPriority:(int)newPriority
{
priority = newPriority;
}
- (BOOL)allowsSelfSignedCertificates
{
return [xmppStream allowsSelfSignedCertificates];
}
- (void)setAllowsSelfSignedCertificates:(BOOL)flag
{
[xmppStream setAllowsSelfSignedCertificates:flag];
}
- (BOOL)isDisconnected
{
return [xmppStream isDisconnected];
}
- (BOOL)isConnected
{
return [xmppStream isConnected];
}
- (BOOL)isSecure
{
return [xmppStream isSecure];
}
- (BOOL)autoLogin
{
return (flags & kAutoLogin);
}
- (void)setAutoLogin:(BOOL)flag
{
if(flag)
flags |= kAutoLogin;
else
flags &= ~kAutoLogin;
}
- (BOOL)autoRoster
{
return (flags & kAutoRoster);
}
- (void)setAutoRoster:(BOOL)flag
{
if(flag)
flags |= kAutoRoster;
else
flags &= ~kAutoRoster;
}
- (BOOL)autoPresence
{
return (flags & kAutoPresence);
}
- (void)setAutoPresence:(BOOL)flag
{
if(flag)
flags |= kAutoPresence;
else
flags &= ~kAutoPresence;
}
- (BOOL)autoReconnect
{
return (flags & kAutoReconnect);
}
- (void)setAutoReconnect:(BOOL)flag
{
if(flag)
flags |= kAutoReconnect;
else
flags &= ~kAutoReconnect;
}
- (BOOL)shouldReconnect
{
return (flags & kShouldReconnect);
}
- (void)setShouldReconnect:(BOOL)flag
{
if(flag)
flags |= kShouldReconnect;
else
flags &= ~kShouldReconnect;
}
- (BOOL)hasRoster
{
return (flags & kHasRoster);
}
- (void)setHasRoster:(BOOL)flag
{
if(flag)
flags |= kHasRoster;
else
flags &= ~kHasRoster;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Connecting, Registering and Authenticating
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)connect
{
[self onConnecting];
if([self usesOldStyleSSL])
[xmppStream connectToSecureHost:domain onPort:port withVirtualHost:[myJID domain]];
else
[xmppStream connectToHost:domain onPort:port withVirtualHost:[myJID domain]];
}
- (void)disconnect
{
// Turn off the shouldReconnect flag.
// This flag will tell us that we should not automatically attempt to reconnect when the connection closes.
[self setShouldReconnect:NO];
[xmppStream disconnect];
}
- (BOOL)supportsInBandRegistration
{
return [xmppStream supportsInBandRegistration];
}
- (void)registerUser
{
[xmppStream registerUser:[myJID user] withPassword:password];
}
- (BOOL)supportsPlainAuthentication
{
return [xmppStream supportsPlainAuthentication];
}
- (BOOL)supportsDigestMD5Authentication
{
return [xmppStream supportsDigestMD5Authentication];
}
- (BOOL)allowsPlaintextAuth
{
return (flags & kAllowsPlaintextAuth);
}
- (void)setAllowsPlaintextAuth:(BOOL)flag
{
if(flag)
flags |= kAllowsPlaintextAuth;
else
flags &= ~kAllowsPlaintextAuth;
}
- (void)authenticateUser
{
if(![self allowsPlaintextAuth])
{
if(![xmppStream isSecure] && ![xmppStream supportsDigestMD5Authentication])
{
// The only way to login is via plaintext!
return;
}
}
[xmppStream authenticateUser:[myJID user] withPassword:password resource:[myJID resource]];
}
- (BOOL)isAuthenticated
{
return [xmppStream isAuthenticated];
}
- (NSError *)streamError
{
return streamError;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Presence Managment
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)goOnline
{
NSString *priorityStr = [NSString stringWithFormat:@"%i", priority];
NSXMLElement *presence = [NSXMLElement elementWithName:@"presence"];
[presence addChild:[NSXMLElement elementWithName:@"priority" stringValue:priorityStr]];
[xmppStream sendElement:presence];
}
- (void)goOffline
{
// Send offline presence element
NSXMLElement *presence = [NSXMLElement elementWithName:@"presence"];
[presence addAttributeWithName:@"type" stringValue:@"unavailable"];
[xmppStream sendElement:presence];
// Remove all users from our roster when we're offline.
// We don't receive presence notifications when we're offline.
BOOL didUpdateRoster = ([roster count] > 0);
[roster removeAllObjects];
[self setHasRoster:NO];
if(didUpdateRoster)
{
[self onDidUpdateRoster];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Roster Managment
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)fetchRoster
{
NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
[iq addAttributeWithName:@"type" stringValue:@"get"];
[iq addChild:query];
[xmppStream sendElement:iq];
}
- (void)addBuddy:(XMPPJID *)jid withNickname:(NSString *)optionalName
{
if(jid == nil) return;
if([[myJID bare] isEqualToString:[jid bare]])
{
// No, you don't need to add yourself
return;
}
// Add the buddy to our roster
NSXMLElement *item = [NSXMLElement elementWithName:@"item"];
[item addAttributeWithName:@"jid" stringValue:[jid bare]];
if(optionalName)
{
[item addAttributeWithName:@"name" stringValue:optionalName];
}
NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
[query addChild:item];
NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
[iq addAttributeWithName:@"type" stringValue:@"set"];
[iq addChild:query];
[xmppStream sendElement:iq];
// Subscribe to the buddy's presence
NSXMLElement *presence = [NSXMLElement elementWithName:@"presence"];
[presence addAttributeWithName:@"to" stringValue:[jid bare]];
[presence addAttributeWithName:@"type" stringValue:@"subscribe"];
[xmppStream sendElement:presence];
}
- (void)removeBuddy:(XMPPJID *)jid
{
if(jid == nil) return;
if([[myJID bare] isEqualToString:[jid bare]])
{
// No, you shouldn't remove yourself
return;
}
// Remove the buddy from our roster
// Unsubscribe from presence
// And revoke contact's subscription to our presence
// ...all in one step
NSXMLElement *item = [NSXMLElement elementWithName:@"item"];
[item addAttributeWithName:@"jid" stringValue:[jid bare]];
[item addAttributeWithName:@"subscription" stringValue:@"remove"];
NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
[query addChild:item];
NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
[iq addAttributeWithName:@"type" stringValue:@"set"];
[iq addChild:query];
[xmppStream sendElement:iq];
}
- (void)setNickname:(NSString *)nickname forBuddy:(XMPPJID *)jid
{
if(jid == nil) return;
NSXMLElement *item = [NSXMLElement elementWithName:@"item"];
[item addAttributeWithName:@"jid" stringValue:[jid bare]];
[item addAttributeWithName:@"name" stringValue:nickname];
NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
[query addChild:item];
NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
[iq addAttributeWithName:@"type" stringValue:@"set"];
[iq addChild:query];
[xmppStream sendElement:iq];
}
- (void)acceptBuddyRequest:(XMPPJID *)jid
{
// Send presence response
NSXMLElement *response = [NSXMLElement elementWithName:@"presence"];
[response addAttributeWithName:@"to" stringValue:[jid bare]];
[response addAttributeWithName:@"type" stringValue:@"subscribed"];
[xmppStream sendElement:response];
// Add user to our roster
NSXMLElement *item = [NSXMLElement elementWithName:@"item"];
[item addAttributeWithName:@"jid" stringValue:[jid bare]];
NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
[query addChild:item];
NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
[iq addAttributeWithName:@"type" stringValue:@"set"];
[iq addChild:query];
[xmppStream sendElement:iq];
// Subscribe to the user's presence
NSXMLElement *presence = [NSXMLElement elementWithName:@"presence"];
[presence addAttributeWithName:@"to" stringValue:[jid bare]];
[presence addAttributeWithName:@"type" stringValue:@"subscribe"];
[xmppStream sendElement:presence];
}
- (void)rejectBuddyRequest:(XMPPJID *)jid
{
// Send presence response
NSXMLElement *response = [NSXMLElement elementWithName:@"presence"];
[response addAttributeWithName:@"to" stringValue:[jid bare]];
[response addAttributeWithName:@"type" stringValue:@"unsubscribed"];
[xmppStream sendElement:response];
}
- (NSArray *)sortedUsersByName
{
return [[roster allValues] sortedArrayUsingSelector:@selector(compareByName:)];
}
- (NSArray *)sortedUsersByAvailabilityName
{
return [[roster allValues] sortedArrayUsingSelector:@selector(compareByAvailabilityName:)];
}
- (NSArray *)sortedAvailableUsersByName
{
return [[self unsortedAvailableUsers] sortedArrayUsingSelector:@selector(compareByName:)];
}
- (NSArray *)sortedUnavailableUsersByName
{
return [[self unsortedUnavailableUsers] sortedArrayUsingSelector:@selector(compareByName:)];
}
- (NSArray *)unsortedUsers
{
return [roster allValues];
}
- (NSArray *)unsortedAvailableUsers
{
NSArray *allUsers = [roster allValues];
NSMutableArray *result = [NSMutableArray arrayWithCapacity:[allUsers count]];
int i;
for(i = 0; i < [allUsers count]; i++)
{
XMPPUser *currentUser = [allUsers objectAtIndex:i];
if([currentUser isOnline])
{
[result addObject:currentUser];
}
}
return result;
}
- (NSArray *)unsortedUnavailableUsers
{
NSArray *allUsers = [roster allValues];
NSMutableArray *result = [NSMutableArray arrayWithCapacity:[allUsers count]];
int i;
for(i = 0; i < [allUsers count]; i++)
{
XMPPUser *currentUser = [allUsers objectAtIndex:i];
if(![currentUser isOnline])
{
[result addObject:currentUser];
}
}
return result;
}
- (NSArray *)sortedResources:(BOOL)includeResourcesForMyUserExcludingMyself
{
// Add all the resouces from all the available users in the roster
NSArray *availableUsers = [self unsortedAvailableUsers];
NSMutableArray *result = [NSMutableArray arrayWithCapacity:[availableUsers count]];
NSUInteger i;
for(i = 0; i < [availableUsers count]; i++)
{
XMPPUser *user = [availableUsers objectAtIndex:i];
[result addObjectsFromArray:[user unsortedResources]];
}
if(includeResourcesForMyUserExcludingMyself)
{
// Now add all the available resources from our own user account (excluding ourselves)
NSArray *myResources = [myUser unsortedResources];
for(i = 0; i < [myResources count]; i++)
{
XMPPResource *resource = [myResources objectAtIndex:i];
if(![myJID isEqual:[resource jid]])
{
[result addObject:resource];
}
}
}
return [result sortedArrayUsingSelector:@selector(compare:)];
}
- (XMPPUser *)userForJID:(XMPPJID *)jid
{
XMPPUser *result = [roster objectForKey:[jid bareJID]];
if(result)
{
return result;
}
if([[jid bareJID] isEqual:[myJID bareJID]])
{
return myUser;
}
return nil;
}
- (XMPPResource *)resourceForJID:(XMPPJID *)jid
{
XMPPUser *user = [self userForJID:jid];
return [user resourceForJID:jid];
}
- (XMPPUser *)myUser
{
return [[myUser retain] autorelease];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Sending Elements:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)sendElement:(NSXMLElement *)element
{
[xmppStream sendElement:element];
}
- (void)sendElement:(NSXMLElement *)element andNotifyMe:(long)tag
{
[xmppStream sendElement:element andNotifyMe:tag];
}
- (void)sendMessage:(NSString *)message toJID:(XMPPJID *)jid
{
NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
[body setStringValue:message];
NSXMLElement *element = [NSXMLElement elementWithName:@"message"];
[element addAttributeWithName:@"type" stringValue:@"chat"];
[element addAttributeWithName:@"to" stringValue:[jid full]];
[element addChild:body];
[self sendElement:element];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Delegate Helper Methods:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)onConnecting
{
[multicastDelegate xmppClientConnecting:self];
}
- (void)onDidConnect
{
[multicastDelegate xmppClientDidConnect:self];
}
- (void)onDidDisconnect
{
[multicastDelegate xmppClientDidDisconnect:self];
}
- (void)onDidRegister
{
[multicastDelegate xmppClientDidRegister:self];
}
- (void)onDidNotRegister:(NSXMLElement *)error
{
[multicastDelegate xmppClient:self didNotRegister:error];
}
- (void)onDidAuthenticate
{
[multicastDelegate xmppClientDidAuthenticate:self];
}
- (void)onDidNotAuthenticate:(NSXMLElement *)error
{
[multicastDelegate xmppClient:self didNotAuthenticate:error];
}
- (void)onDidUpdateRoster
{
[multicastDelegate xmppClientDidUpdateRoster:self];
}
- (void)onDidReceiveBuddyRequest:(XMPPJID *)jid
{
[multicastDelegate xmppClient:self didReceiveBuddyRequest:jid];
}
- (void)onDidReceiveIQ:(XMPPIQ *)iq
{
[multicastDelegate xmppClient:self didReceiveIQ:iq];
}
- (void)onDidReceiveMessage:(XMPPMessage *)message
{
[multicastDelegate xmppClient:self didReceiveMessage:message];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPStream Delegate Methods:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppStreamDidOpen:(XMPPStream *)sender
{
[self onDidConnect];
if([self autoLogin])
{
[self authenticateUser];
}
}
- (void)xmppStreamDidRegister:(XMPPStream *)sender
{
[self onDidRegister];
}
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error
{
[self onDidNotRegister:error];
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
// We're now connected and properly authenticated
// Should we get accidentally disconnected we should automatically reconnect (if kAutoReconnect is set)
[self setShouldReconnect:YES];
// Update myUser
[myUser release];
myUser = [[XMPPUser alloc] initWithJID:myJID];
// Note: Order matters in the calls below.
// We request the roster FIRST, because we need the roster before we can process any presence notifications.
// We shouldn't receive any presence notification until we've set our presence to available.
//
// We notify the delegate(s) LAST because delegates may be sending their own custom
// presence packets (and have set autoPresence to NO). The logical place for them to do so is in the
// onDidAuthenticate method, so we try to request the roster before they start
// sending any presence packets.
//
// In the event that we do receive any presence elements prior to receiving our roster,
// we'll be forced to store them in the earlyPresenceElements array, and process them after we finally
// get our roster list.
if([self autoRoster])
{
[self fetchRoster];
}
if([self autoPresence])
{
[self goOnline];
}
[self onDidAuthenticate];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
[self onDidNotAuthenticate:error];
}
- (void)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
if([iq isRosterQuery])
{
// Note: Some jabber servers send an iq element with a xmlns.
// Because of the bug in Apple's NSXML (documented in our elementForName method),
// it is important we specify the xmlns for the query.
NSXMLElement *query = [iq elementForName:@"query" xmlns:@"jabber:iq:roster"];
NSArray *items = [query elementsForName:@"item"];
int i;
for(i = 0; i < [items count]; i++)
{
NSXMLElement *item = (NSXMLElement *)[items objectAtIndex:i];
// Filter out items for users who aren't actually in our roster.
// That is, those users who have requested to be our buddy, but we haven't approved yet.
if([XMPPIQ isRosterItem:item])
{
NSString *jidStr = [[item attributeForName:@"jid"] stringValue];
XMPPJID *jid = [XMPPJID jidWithString:jidStr];
NSString *subscription = [[item attributeForName:@"subscription"] stringValue];
if([subscription isEqualToString:@"remove"])
{
[roster removeObjectForKey:jid];
}
else
{
XMPPUser *user = [roster objectForKey:jid];
if(user)
{
[user updateWithItem:item];
}
else
{
XMPPUser *newUser = [[XMPPUser alloc] initWithItem:item];
[roster setObject:newUser forKey:jid];
[newUser release];
}
}
}
}
[self onDidUpdateRoster];
if(![self hasRoster])
{
// We should have our roster now
[self setHasRoster:YES];
// Which means we can process any premature presence elements we received
for(i = 0; i < [earlyPresenceElements count]; i++)
{
[self xmppStream:xmppStream didReceivePresence:[earlyPresenceElements objectAtIndex:i]];
}
[earlyPresenceElements removeAllObjects];
}
}
else
{
[self onDidReceiveIQ:iq];
}
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
[self onDidReceiveMessage:message];
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
if(![self hasRoster])
{
// We received a presence notification, but we don't have a roster to apply it to yet.
// We store the presence element until we get our roster.
[earlyPresenceElements addObject:presence];
return;
}
if([[presence type] isEqualToString:@"subscribe"])
{
XMPPUser *user = [roster objectForKey:[[presence from] bareJID]];
if(user && [self autoRoster])
{
// Presence subscription request from someone who's already in our roster
// Automatically approve
NSXMLElement *response = [NSXMLElement elementWithName:@"presence"];
[response addAttributeWithName:@"to" stringValue:[[presence from] bare]];
[response addAttributeWithName:@"type" stringValue:@"subscribed"];
[xmppStream sendElement:response];
}
else
{
// Presence subscription request from someone who's NOT in our roster
[self onDidReceiveBuddyRequest:[presence from]];
}
}
else
{
XMPPUser *rosterUser = [roster objectForKey:[[presence from] bareJID]];
if(rosterUser)
{
[rosterUser updateWithPresence:presence];
}
else if([[myJID bareJID] isEqual:[[presence from] bareJID]])
{
[myUser updateWithPresence:presence];
}
[self onDidUpdateRoster];
}
}
/**
* There are two types of errors: TCP errors and XMPP errors.
* If a TCP error is encountered (failure to connect, broken connection, etc) a standard NSError object is passed.
* If an XMPP error is encountered (<stream:error> for example) an NSXMLElement object is passed.
*
* Note that standard errors (<iq type='error'/> for example) are delivered normally,
* via the other didReceive...: methods.
**/
- (void)xmppStream:(XMPPStream *)xs didReceiveError:(id)error
{
if([error isKindOfClass:[NSError class]])
{
[streamError autorelease];
streamError = [(NSError *)error copy];
if([xmppStream isAuthenticated])
{
// We were fully connected to the XMPP server, but we've been disconnected for some reason.
// We will wait for a few seconds or so, and then attempt to reconnect if possible
[self performSelector:@selector(attemptReconnect:) withObject:nil afterDelay:4.0];
}
}
}
- (void)xmppStreamDidClose:(XMPPStream *)sender
{
[roster removeAllObjects];
[self setHasRoster:NO];
[myUser release];
myUser = nil;
[self onDidDisconnect];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Reconnecting
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* This method is invoked a few seconds after a disconnection from the server,
* or after we receive notification that we may once again have a working internet connection.
* If we are still disconnected, it will attempt to reconnect if the network connection appears to be online.
**/
- (void)attemptReconnect:(id)ignore
{
NSLog(@"XMPPClient: attempReconnect method called...");
if([xmppStream isDisconnected] && [self autoReconnect] && [self shouldReconnect])
{
SCNetworkConnectionFlags reachabilityStatus;
BOOL success = SCNetworkCheckReachabilityByName("www.deusty.com", &reachabilityStatus);
if(success && (reachabilityStatus & kSCNetworkFlagsReachable))
{
[self connect];
}
}
}
- (void)networkStatusDidChange:(NSNotification *)notification
{
// The following information needs to be tested using multiple interfaces
// If this is a notification of a lost internet connection, there won't be a userInfo
// Otherwise, there will be...I think...
if([notification userInfo])
{
// We may have an internet connection now...
//
// If we were accidentally disconnected (user didn't tell us to disconnect)
// then now would be a good time to attempt to reconnect.
if([self shouldReconnect])